在Java中调用子类的方法

eye*_*ate 15 java

如果我有一个基类 Base thing = null; ,其中有一个子类 class Subclass extends Base ,我就是 thing = new Subclass 如何调用一个特别在Subclass中的方法,而不是在Base中?恩. Base只有method() Subclass具有method()specialMethod() 该方法specialMethod()是一个我想打电话.

Eri*_*oom 16

如果你知道thing包含a Subclass,你可以这样做:

((Subclass) thing).specialMethod()
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果thing不是`Subclass`,那么它将使用`ClassCastException`进行炸弹...如果您不确定,请使用`instanceof`来检查`thing`是否是`Subclass`. (6认同)

Esk*_*ola 16

其他人已经提到过如何投射物体来回答你的问题,但首先提出这个问题就指出了一个可能的设计问题.一些可能的原因:


Osc*_*Ryz 9

您必须cast能够调用该方法:

Base thing = new SubClass();

((SubClass) thing ).specialMethod();
Run Code Online (Sandbox Code Playgroud)

如果您遇到这种情况,很可能您没有正确的界面(正确的方法集)

在深入到您开始验证所有内容以了解是否可以调用某个方法的阶段之前:

 public void x ( Base thing ) {
     if( thing.instanceof Subclass ) {
         ((SubClass)thing).specialMethod();
     }
 }
Run Code Online (Sandbox Code Playgroud)

考虑一下,如果您不需要specialMethod在层次结构中向上移动,那么它就属于基础.

如果你肯定不需要它在基础中,但你需要它在子类中至少考虑使用正确的类型:

 SubClass thing = ... 
 // no need to cast
 thing.specialMethod();
Run Code Online (Sandbox Code Playgroud)

但一如既往,这取决于你想做什么.