I am trying to learn about inheritance and I came across this problem.
Here is the code:
System.out.println("show from parent");
class Child extends Parent
public static void main(String s)
Parent p=new Child();
System.out.println("show from child");
System.out.println("display from child");
Child.java:15: error: cannot find symbol
symbol: method display()
location: variable p of type Parent
You must understand the distinction between the run time type and the compile time type.
At run time your variable
p holds a reference to a
Child instance. So calling the
show method will run the code in
Child#show because this overrides the method
At compile time, the compiler can only know about the declared type of the variable. And this is
Parent. So the compiler can only allow access to the fields and methods of type
Parent, but not of type
display method simply isn't declared in
Parent, hence the error.