简体   繁体   English

为什么以下代码给出错误?

[英]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. 如果我能够访问show()那么为什么知道知道display()是继承的并且也存在于Child class.的类定义中而无法访问display() 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. 在运行时,变量p拥有对Child实例的引用。 So calling the show method will run the code in Child#show because this overrides the method Parent#show . 因此,调用show方法将在Child#show运行代码,因为这将覆盖方法Parent#show

At compile time, the compiler can only know about the declared type of the variable. 在编译时,编译器只能知道变量的声明类型 And this is Parent . 这是Parent So the compiler can only allow access to the fields and methods of type Parent , but not of type Child . 因此,编译器只能允许访问类型为Parent的字段和方法,而不能访问类型为Child的字段和方法。

The display method simply isn't declared in Parent , hence the error. display方法只是没有在Parent声明,因此是错误的。

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(); 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方法而不是子类。如果您尝试使用对象访问父类中的方法,则不需要子类中的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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