Java 在 parent class 的 children 上进行模式匹配
Java pattern matching on children of a parent class
我有一个 Parent
class 和一个 child class,extends Parent
叫 Child
。我有一个方法 run
可以采用 Parent
或 Child
实例。我使用代码 Parent child = new Child()
创建了一个 Child
实例。请参阅下面的代码。
我希望代码输出“你是 child”,但我收到的却是“你是 parent”。我理解这背后的原因,但是我想知道我可以使用什么来执行 run
的 Child
实现。
在我的系统中,我将有多个继承自 Parent
的“child”classes 和满足每个“child 的多个 run
方法]" class。结果,转换将不起作用,因此如果您在解决方案中包含转换,恐怕对我没有帮助。我对此的灵感或多或少来自 Haskell.
等语言中的模式匹配。
public class Child extends Parent {
public static void main(String[] args) {
Parent child = new Child();
run(child);
}
public static void run(Child child) {
System.out.println("You are a child");
}
public static void run(Parent parent) {
System.out.println("You are a parent");
}
}
不要使用静态方法。将方法添加到您的对象并覆盖它们。
class Parent {
public void run() {
System.out.println("You are a parent");
}
}
class Child extends Parent {
@Override
public void run() {
System.out.println("You are a child");
}
}
class Test {
public static void main(String[] args) {
Parent child = new Child();
child.run(); // <- prints "you are a child"
}
}
评估调用哪个方法是编译的一部分。在您的代码中,您将 new Child
存储为 Parent
变量,因此从编译器的角度来看,它只知道您有一个 Parent
,因此它解析了对该方法的调用。
如果要显示 'You are a child',您需要将变量声明为 Child
,或者使用一种方法对类型进行一些运行时检查(类似于 if (item instanceof Child) { ... }
).
我有一个 Parent
class 和一个 child class,extends Parent
叫 Child
。我有一个方法 run
可以采用 Parent
或 Child
实例。我使用代码 Parent child = new Child()
创建了一个 Child
实例。请参阅下面的代码。
我希望代码输出“你是 child”,但我收到的却是“你是 parent”。我理解这背后的原因,但是我想知道我可以使用什么来执行 run
的 Child
实现。
在我的系统中,我将有多个继承自 Parent
的“child”classes 和满足每个“child 的多个 run
方法]" class。结果,转换将不起作用,因此如果您在解决方案中包含转换,恐怕对我没有帮助。我对此的灵感或多或少来自 Haskell.
public class Child extends Parent {
public static void main(String[] args) {
Parent child = new Child();
run(child);
}
public static void run(Child child) {
System.out.println("You are a child");
}
public static void run(Parent parent) {
System.out.println("You are a parent");
}
}
不要使用静态方法。将方法添加到您的对象并覆盖它们。
class Parent {
public void run() {
System.out.println("You are a parent");
}
}
class Child extends Parent {
@Override
public void run() {
System.out.println("You are a child");
}
}
class Test {
public static void main(String[] args) {
Parent child = new Child();
child.run(); // <- prints "you are a child"
}
}
评估调用哪个方法是编译的一部分。在您的代码中,您将 new Child
存储为 Parent
变量,因此从编译器的角度来看,它只知道您有一个 Parent
,因此它解析了对该方法的调用。
如果要显示 'You are a child',您需要将变量声明为 Child
,或者使用一种方法对类型进行一些运行时检查(类似于 if (item instanceof Child) { ... }
).