a874 a874 - 7 months ago 9
Java Question

Why does the following code gives an error?

I am trying to learn about inheritance and I came across this problem.

Here is the code:

import java.util.*;
class Parent
{
void show()
{
System.out.println("show from parent");
}
}
class Child extends Parent
{
public static void main(String s[])
{
Parent p=new Child();
p.show();
p.display();
}
void show()
{
System.out.println("show from child");
}
void display()
{
System.out.println("display from child");
}
}


And the error is:

G:\javap>javac Child.java
Child.java:15: error: cannot find symbol
p.display();
^
symbol: method display()
location: variable p of type Parent
1 error


If I'm able to access
show()
then why am I not able to access
display()
knowing that
display()
is inherited and is also present in the class definition of
Child class.

Answer

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 Parent#show.

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 Child.

The display method simply isn't declared in Parent, hence the error.