繁体   English   中英

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

[英]Calling method that exists in child classes but not in parent class

public class Parent {
    ....
}

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

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

这里,方法foo()仅存在于子类中,不能添加到父类中(甚至不能添加到抽象方法中)。 在这种情况下,当我想对作为Parent类的引用的obj调用foo()方法时,则需要将intanceof与多个if..else使用,这是我想避免的。

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

编辑:我只需要使用obj类型作为Parent 否则,我将无法在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()被调用。

除非在父类/接口本身中声明了除非方法,否则您不能使用父对象引用来执行此操作。

您必须将其转换为子类,因为父类/接口除了它们之间定义的协定之外,对子类没有任何了解。

在这里, 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() {

    }
}

我最终采用的方法是使用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

您可以实现从Parent继承的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM