【问题标题】:Call a method of subclass in Java在Java中调用子类的方法
【发布时间】:2011-02-11 16:07:16
【问题描述】:

如果我有一个基类 Base thing = null; 其中有一个子类 class Subclass extends Base 我煽动它 thing = new Subclass 我将如何调用专门在子类中但不在 Base 中的方法? 前任。 Base 只有 method() Subclassmethod()specialMethod() specialMethod() 方法是我要调用的方法。

【问题讨论】:

  • 这通常是个坏主意。如果您知道该对象是 Subclass 类型,那么就这样引用它,您就没有问题。如果该方法确实属于 Base - 将其放在 Base 中。

标签: java


【解决方案1】:

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

((Subclass) thing).specialMethod()

【讨论】:

  • 请注意,如果事情不是Subclass,这将使用ClassCastException 进行轰炸...使用instanceof 来检查thing 是否是Subclass,如果你先不确定。
【解决方案2】:

其他人已经提到了如何通过投射对象来获得问题的答案,但是首先提出这个问题指出了一个可能的设计问题。一些可能的原因:

【讨论】:

  • 只需将其更改为“可能的设计问题”,我完全同意。
【解决方案3】:

你必须cast它才能调用该方法:

Base thing = new SubClass();

((SubClass) thing ).specialMethod();

如果你遇到这种情况,很可能你没有正确的接口(正确的方法集)

在深入开始验证所有内容以了解是否可以调用方法之前:

 public void x ( Base thing ) {
     if( thing.instanceof Subclass ) {
         ((SubClass)thing).specialMethod();
     }
 }

考虑是否不需要将specialMethod 在层次结构中向上移动,使其属于基础。

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

 SubClass thing = ... 
 // no need to cast
 thing.specialMethod();

但与往常一样,这取决于您要做什么。

【讨论】:

    【解决方案4】:

    在 Java 中处理继承/多态时,您会看到基本上两种类型的强制转换:

    向上转型:

    Superclass x = new Subclass();
    

    这是隐含的,不需要强制转换,因为 Java 知道 Superclass 可以做的所有事情,Subclass 也可以做。

    向下转型

    Superclass x = new Subclass();
    
    Subclass y = (Subclass) x;
    

    在这种情况下,您需要进行强制转换,因为 Java 不太确定这是否可行。你必须通过告诉它你知道你在做什么来安慰它。原因是子类可能有一些超类没有的奇怪方法。

    一般来说,如果你想实例化一个类来调用它的子类中的某些东西,你可能应该只实例化子类开始——或者确定方法是否也应该在超类中。

    【讨论】:

      【解决方案5】:

      您必须键入或将事物转换为子类。所以:

            Subclass thing = new Subclass();
      

      或:

           ((Subclass) thing).specialMethod();
      

      【讨论】:

        【解决方案6】:

        另一种方法可能是执行以下操作:

        public abstract class Base {
        
            //method() not implemented
        
            public abstract void specialMethod();
        }
        
        public class Subclass extends Base {
        
            //method() not implemented
        
            @Override
            public void specialMethod() {
               //put your code here
               System.out.println("specialMethod from Subclass");
            }
        }
        

        所以你可以这样做:

        thing.specialMethod();
        

        它会给你:“来自子类的特殊方法”。

        【讨论】:

        • 我今天也经历过同样的事情 :)
        【解决方案7】:

        您可以将您想要调用的方法设为抽象方法并在子类中实现它。然后在你的超类中,像往常一样调用它this.someMethod()。在运行时,它将转到someMethod() 并运行从子类实现的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-22
          • 2015-04-23
          • 1970-01-01
          • 2020-07-15
          • 2019-01-05
          相关资源
          最近更新 更多