Reputation: 3
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?
Upvotes: 0
Views: 91
Reputation: 18313
To expand upon DwB's answer: create a default no-op method.
public class Super {
public void special() {
// no-op
}
}
public class Sub extends Super {
@Override public void special() {
System.out.println("Now I do something");
}
}
Upvotes: 0
Reputation: 38328
create an abstract method in the super class (and change the super to an abstract class) then call the abstract method in the super class.
Upvotes: 0
Reputation: 26185
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");
}
}
Upvotes: 1