asad_hussain
asad_hussain

Reputation: 2001

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.

Upvotes: 0

Views: 77

Answers (3)

Seelenvirtuose
Seelenvirtuose

Reputation: 20618

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.

Upvotes: 7

Sumit Bhatt
Sumit Bhatt

Reputation: 718

if u want to call the display method of client then you must need to create object of child class. eg. Child child=new Child();

otherwise you need to write display method in parent class.

the rules is reference of parent class cant call member of child.

Upvotes: 1

Januka samaranyake
Januka samaranyake

Reputation: 2597

Display() method not in parent class.that is the error .you are access parent class show method not child class.if you are trying to access method in parent class using object you dont need methods in child class

Upvotes: 0

Related Questions