问题: 我的疑问是,为什么p1.a返回相对于父类的值10,尽管p1是子类的对象,却调用子类的display方法
Parent.java
package Inheritance;
public class Parent {
int a =10;
public Parent()
{
System.out.println("Parent");
}
public static void print()
{
System.out.println("Print parent ");
}
public void display()
{
int b=200;
System.out.println("Display parent");
System.out.println(b);
}
}
Child.java
package Inheritance;
public class Child extends Parent {
int a=20;
public Child() {
System.out.println("child");
}
public static void print()
{
System.out.println("Print child");
}
public void display()
{
int b=100;
System.out.println("Display child");
System.out.println(b);
}
}
package Inheritance;
public class MainInheritance {
public static void main(String[] args)
{
Parent p = new Parent();
System.out.println("value "+p.a);
System.out.println("-------------------");
Parent p1 = new Child();
System.out.println("value "+p1.a);
Child.print();
p1.display();
System.out.println("-------------------");
Child c=new Child();
System.out.println("value "+c.a);
}
}
问题: 我的疑问是,为什么p1.a返回相对于父类的值10,尽管p1是子类的对象,却调用子类的display方法