编译时类型由声明该变量时使用的类型决定
运行时类型由实际赋给该变量的对象决定
People people=new Student();
如上所示,people的编译时类型为People,运行时类型为Student
看一下他有什么特性
public class People {
public String name = "people";
public int age = 1;
public void showName() {
System.out.println("People name is " + name);
}
public void showPAge() {
System.out.println("People age is " + age);
}
}
class Student extends People {
public String name = "student";
public int age = 2;
public String address = "北京";
public void showName() {
System.out.println("Student name is " + name);
}
public void showSAge() {
System.out.println("Student age is " + age);
}
public static void main(String[] args) {
People people = new Student();
// Student student=new People(); 报错,说明不存在子类型为编译时类型而父类型为运行时类型的情况
people.showName();
people.showPAge();
// people.showSAge(); 报错 The method showSAge() is undefined for the type People
System.out.println(people.age + people.name);
// System.out.println(people.address); 报错address cannot be resolved or is not a field
}
}
运行结果如下:
由此可推 A a = new B(); (其中A是B的父类)中,对象a
仅可调用父类A的方法,若是子类B重写了A中方法,则调用重写后的方法,对B中方法不可见
使用父类A中的属性,对B中属性不可见