1. 背景
Java中的许多对象(一般都是具有父子类关系的父类对象)在运行时都会出现两种类型,一种是编译时类型,另一种是运行时类型。
2. 编译时类型
编译时类型由声明该变量时使用的类型决定,比如下方代码块中的main函数类声明的person和male引用变量,其实他们的编译类型分别是Person和Male。编译时引用变量只能调用其编译时类型所具有的方法,因此person是只能调用printAge()方法,而不能调用printStudentInfo()方法
3. 运行时类型
运行时类型由实际赋给该变量的对象决定,同样是person和male引用变量,他们的运行是类型都是Student,所以会看到 male.printAge()和person.printAge()方法运行时都是执行Student内部的printAge()方法。引用变量在运行时则执行它运行时类型所具有的方法
4. 两者关系
public class Male extends Person{
int age = 30;
public void printAge() {
System.out.println(this.getClass().getName() + "'s age is " + age);
}
}
public class Student extends Male {
int age = 20;
public void printAge() {
System.out.println(this.getClass().getName() + "'s age is " + age);
}
public void printStudentInfo() {
System.out.println("student info");
}
}
public class Person {
int age = 1;
public void printAge() {
System.out.println(this.getClass().getName() + "'s age is " + age);
}
public static void main(String[] args) {
Student student = new Student();
Male male = student;
Person person = student;
student.printAge();
male.printAge();
person.printAge();
System.out.println(student.age);
System.out.println(male.age);
System.out.println(person.age);
}
}
运行结果如下: