I'm having difficulty wrapping my head around this odd behavior of Java inheritance.
Say, I have Parent class with private method method1. Then there's a class Child that extends Parent class. Child also defines method called method1, but it is public. Please see below for example:
public class Main {
public static void main(String[] args) {
Parent p = new Child();
p.method2();
}
}
class Parent{
private void method1() {
System.out.println ( "Parent's method1()" );
}
public void method2() {
System.out.println ( "Parent's method2()" );
method1();
}
}
class Child extends Parent {
public void method1() {
System.out.println ( "Child's method1()" );
}
}
What I don't understand is that the output is below!!!
Parent's method2()
Parent's method1()
I know that since method1 is private in Parent, method1 in Child has nothing to do with that of Parent. If so, then when method2 invokes method1, why is Parent's method1 is called not Child's? Especially when the actual type is Child.
It seems like there's absolutely no clue which method1 is called from method2. Am I missing a inheritance rule? Please please help!!!