调用存在于子类中但不存在于父类中的方法

public class Parent { .... } public class Child1 extends Parent { .... public void foo() { .... } } public class Child2 extends Parent { .... public void foo() { .... } } 

这里方法foo()只存在于Child类中,不能添加到Parent类(甚至不是抽象方法)。 在这种情况下,当我想在obj上调用foo()方法时,这是Parent类的引用,那么我需要使用intanceof和多个if..else ,我想避免它。

 Parent obj = ...// Object of one of the child classes obj.foo(); 

编辑:我需要使用obj类型作为Parent 。 否则我将无法调用父类中存在的obj上的方法。


我的解决方案:我想的方法是使用foo()方法定义一个接口说FooInterface并让所有子类实现它,然后我可以输入obj到该接口并调用foo()方法,如下所示:

 if(obj instanceof FooInterface){ ((FooInterface)obj).foo(); } 

有更好的方法吗? 或者对这个有什么改进?

多态性应用于对象引用,而不是类型。 你打电话时

 FooInterface obj = ...// Object of one of the child classes obj.foo(); 

调用子类方法foo()

我最终采用的方法是使用foo()方法定义一个接口说FooInterface并让所有子类实现它,然后我可以将obj类型转换为该接口并调用foo()方法,如下所示:

 Parent obj = ...// Object of one of the child classes ..... if(obj instanceof FooInterface){ ((FooInterface)obj).foo(); } 

如果只想进行类型转换,则无需添加接口。 您可以将其类型转换为所需的类并调用该方法。 例

 public class HelloWorld { public static void main(String args[]) throws FileNotFoundException { SuperClass sc =new Child1(); if(sc instanceof Child1)//Do same for Child2 ((Child1)sc).foo(); } } class SuperClass { } class Child1 extends SuperClass{ public void foo(){ System.out.println("From child1"); } } class Child2 extends SuperClass{ public void foo(){ System.out.println("From child2"); } } 

输出:来自child1

在父类/接口本身中声明除非方法之前,您不能使用父对象引用。

您必须将它向下转换为子类,因为父类/接口除了在它们之间定义的合同之外没有任何关于子类的知识。

contract是指abstract methods


您可以尝试这种方式,无需进行检查。

 FooInterface sc =new Child1(); sc.foo(); ... interface FooInterface{ void foo(); } public class Parent { } public class Child1 extends Parent implements FooInterface{ public void foo() { } } public class Child2 extends Parent implements FooInterface{ public void foo() { } } 

您可以实现从Parentinheritance的AbstractChild ,然后扩展此类而不是Parent

 public class Parent { .... } public abstract class AbstractChild extends Parent{ public abstract void foo(); } public class Child1 extends AbstractChild { .... public void foo() { .... } } public class Child2 extends AbstractChild { .... public void foo() { .... } } 

所以你只需要检查你的实例是否是instanceof AbstractChild