编译时类型和运行时类型
编译时类型(compile-time type)和运行时类型(run-time type)区别
看完这个发生疑问:
Java编译时类型和运行时类型
自己的测试代码如下:
- Parent
package typetest;
public class Parent {
public int age;
public Parent() {
this.age = 30;
}
public void hello() {
System.out.println("Parent hello");
}
}
- Son
注意这里Son中声明了和Parent中相同类型和名称的属性int age。
package typetest;
public class Son extends Parent {
public int age;
public Son() {
this.age = 3;
}
@Override
public void hello() {
System.out.println("Son hello");
}
}
- Test类
package typetest;
public class ComplieTypeAndRuntimeType {
public static void main(String[] args) {
Parent people = new Son();
people.hello(); // Son hello
/*
子类声明了与父类相同的属性时(覆盖父类属性?), 变量调用编译时类型属性 people.age = 30
子类没有覆盖父类属性时,变量调用运行时类型属性 people.age = 3
*/
System.out.println(people.age); // 30
Parent parent = new Parent();
parent.hello(); // Parent hello
System.out.println(parent.age); // 30
Son son = new Son();
son.hello(); // Son hello
System.out.println(son.age); // 3
// ClassCastException
Son people2 = (Son) new Parent();
people2.hello();
System.out.println(people2.age);
}
}
此时输出people.age的结果是30,people.hello()输出的Parent hello。即符合博文中的结论。
第二次测试
将Son中声明的age去掉
package typetest;
public class Son extends Parent {
// public int age;
public Son() {
this.age = 3;
}
@Override
public void hello() {
System.out.println("Son hello");
}
}
此时测试中,people.age的结果是3。
那么,为什么?
OK是我傻叉子了,看图。

image.png
当Son中将自己的age属性去掉后,this.age修改的实际是Parent中的属性age。
因此people.age调用仍然是Parent中的age属性,而在运行时创建Son对象时,Parent的age属性的值被修改为3。
作者:小黑孩er
链接:https://www.jianshu.com/p/8cb385390ed9
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

浙公网安备 33010602011771号