Please consider the following classes:
public interface BaseInterface {
void method1();
void method2();
void method3();
}
public class BaseClass implements BaseInterface {
@Override
public void method1() {
System.out.println("BaseClass.method1 IN");
this.method3();
System.out.println("BaseClass.method1 OUT");
}
@Override
public void method2() {
System.out.println("BaseClass.method2 IN");
System.out.println("BaseClass.method2 OUT");
}
@Override
public void method3() {
System.out.println("BaseClass.method3 IN");
System.out.println("BaseClass.method3 OUT");
}
}
public class ChildClass extends BaseClass {
@Override
public void method1() {
System.out.println("ChildClass.method1 IN");
super.method1();
System.out.println("ChildClass.method1 OUT");
}
@Override
public void method2() {
System.out.println("ChildClass.method2 IN");
super.method2();
System.out.println("ChildClass.method2 OUT");
}
@Override
public void method3() {
System.out.println("ChildClass.method3 IN");
System.out.println("ChildClass.method3()");
System.out.println("ChildClass.method3 OUT");
}
}
In this case, if I create an instance of ChildClass
:
BaseInterface cc1 = new ChildClass();
and then run method1
of this class
cc1.method1();
it will return the following output:
ChildClass.method1 IN
BaseClass.method1 IN
ChildClass.method3 IN
ChildClass.method3()
ChildClass.method3 OUT
BaseClass.method1 OUT
ChildClass.method1 OUT
So when I call this.method3()
(or just method3()
) from the super class (BaseClass
), the method3
of the ChildClass
is executed instead. I know this is the expected behavior but I just wonder how can I still call the BaseClass.method3
in this setup? Is this possible?
Please note that this is a purely theoretical question and I understand that in reality I probably should've instantiated a BaseClass
instance in the first place. Is this the only way to get around that?