简体   繁体   中英

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.

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.

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.

Display()方法不在父类中,这是错误。您正在访问父类show方法而不是子类。如果您尝试使用对象访问父类中的方法,则不需要子类中的方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM