If I have 2 classes, one being the parent with the following:
public class Parent {
...
public void method1() {
method2();
}
public void method2() {
}
}
And then in the subclass
public class Child extends Parent {
...
public void method2() {
...
}
}
If I run the following code:
Child c = new Child();
c.method1();
Which version of method2 gets called?
All methods are virtual in Java, which means that it is the
Child.method2that will be called (even if the call is done from the context ofParent).If the correctness of
Parent.method1relies on the implementation ofmethod2, you should design it differently: