Antonio Banderas Antonio Banderas - 1 month ago 14
Java Question

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?

Answer

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.

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");
  }
}