简体   繁体   English

Java超类调用在子类中创建的方法

[英]Java superclass calling a method created in a subclass

I have a question about Inheritance and Binding. 我有一个关于继承和绑定的问题。

What if I create a new method in a subclass, and try to call it with the superclass reference? 如果我在子类中创建一个新方法,并尝试使用超类引用进行调用怎么办?

I know that it will check first the type, and after that the object. 我知道它将首先检查类型,然后再检查对象。 So according to the rules this is not going work, because this method is not declared in superclass. 因此,根据规则,这是行不通的,因为该方法未在超类中声明。

But is there no way to overcome it? 但是没有办法克服吗?

I mean does Inheritance mean, that you must declare every single method in superclass, and if you would like to change something for subclass, you can only override it? 我的意思是继承是指您必须声明超类中的每个方法,并且如果您想为子类更改某些内容,则只能覆盖它? So if suddenly I realise, that one of my subclasses does needs a special method, or needs an overloading, then I eather forced to declare it in superclass first or forget about it at all? 因此,如果突然意识到我的一个子类确实需要一种特殊的方法,或者需要重载,那么我宁可被迫首先在超类中声明它还是根本不去考虑它?

So if suddenly I realise, that one of my subclasses does needs a special method, or needs an overloading, then I eather forced to declare it in superclass first or forget about it at all? 因此,如果突然意识到我的一个子类确实需要一种特殊的方法,或者需要重载,那么我宁可被迫首先在超类中声明它还是根本不去考虑它?

There is a third option. 还有第三种选择。 Declare the method in the subclass. 在子类中声明方法。 In code that needs to call the method, cast the reference to the subclass type. 在需要调用该方法的代码中,将引用转换为子类类型。 If the reference does not really point to an object of that subclass, you will get a ClassCastException. 如果引用没有真正指向该子类的对象,则将获得ClassCastException。

If you end up having to do this sort of thing you should take another look at it during your next refactoring pass to see if it can be smoothed out. 如果最终不得不做这种事情,那么在下一次重构过程中应该再看一看,看看是否可以解决。

public class Test {
  public static void main(String[] args) {
    System.out.println(new Test().toString());
    Test sub = new TestSub();
    System.out.println(sub.toString());
    ((TestSub)sub).specialMethod();
  }

  @Override
  public String toString(){
    return "I'm a Test";
  }
}

class TestSub extends Test {
  void specialMethod() {
    System.out.println("I'm a TestSub");
  }
}

在父类中创建一个抽象方法(并将父类更改为一个抽象类),然后在父类中调用该抽象方法。

To expand upon DwB's answer: create a default no-op method. 为了扩展DwB的答案:创建默认的不操作方法。

public class Super {
    public void special() {
        // no-op
    }
}

public class Sub extends Super {
    @Override public void special() {
        System.out.println("Now I do something");
    }
}

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

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