调用存在于子类中但不存在于父类中的方法 [英] Calling method that exists in child classes but not in parent class

查看:386
本文介绍了调用存在于子类中但不存在于父类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 我想要的避免。

Here method foo() only exists in the Child classes and CAN NOT be added to the Parent class (not even abstract method). In this situation when I want to call the foo() method on obj which is Parent class's reference then I need to use intanceof with multiple if..else which I want to avoid.

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

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

I Need to use type of obj as Parent only. Else I will not be able to call methods on obj which exists in Parent class.

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

My Solution: The approach that I am thinking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:

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

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

Is there a better approach ? Or any improvement to this one?

推荐答案

我最终采取的方法是定义一个接口说 FooInterface 使用 foo()方法并让所有子类实现它,然后我可以输入obj到该接口并调用 foo()这样的方法:

The approach that I am finally taking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:

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

这篇关于调用存在于子类中但不存在于父类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆