Java中类中数据域与静态方法不具有多态性,仅有普通的方法调用具有多态性
程序员文章站
2022-05-28 17:06:22
...
类中域与静态方法的调用是在编译期进行解析的,不具有多态性。
在实际的工程中,通常会将域设置为private的,可通过构造get方法返回相应的域,不会直接进行访问;而且,在父类与子类中一般也不会定义名字相同的域。
测试程序如下所示:
package com.naruto.chapter8.FieldAccesstest;
import static net.mindview.util.Print.*;
public class FieldAccess {
public static void main(String[] args) {
// TODO Auto-generated method stub
Father sup = new Son();
print("sup.field = " + sup.field + ", sup.getField() = " + sup.getField() + ", ((son)sup).getField() = " + ((Son)sup).getField() + ", ((son)sup).getSuperField() = " + ((Son)sup).getSuperField() + ", ((son)sub).Field = " + ((Son)sup).field);
print("sup.dataFather = " + sup.dataFather + ", ((Son)sup).dataFather = " + ((Son)sup).dataFather + ", ((Son)sup).dataSon = " + ((Son)sup).dataSon);
Son sub = new Son();
print("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() + ", (sub).getField() = " + (sub).getField() + ", ((son)sub).getSuperField() = " + (sub).getSuperField()+ ", ((Father)sub).getField() = " + ((Father)sub).getField()+ ", ((Father)sub).field = " + ((Father)sub).field);
print("sub.dataFather = " + sub.dataFather + ", ((Father)sub).dataFather = " + ((Father)sub).dataFather + ", (sub).dataSon = " + (sub).dataSon);
}
}
class Father {
public int field = 0;
public String dataFather = "Father Data";
public int getField() {
return field;
}
}
class Son extends Father {
public int field = 9;
public String dataSon = "Son Data";
public int getField() {
return field;
}
public int getSuperField() {
return super.field;
}
}
输出:
sup.field = 0, sup.getField() = 9, ((son)sup).getField() = 9, ((son)sup).getSuperField() = 0, ((son)sub).Field = 9
sup.dataFather = Father Data, ((Son)sup).dataFather = Father Data, ((Son)sup).dataSon = Son Data
sub.field = 9, sub.getField() = 9, (sub).getField() = 9, ((son)sub).getSuperField() = 0, ((Father)sub).getField() = 9, ((Father)sub).field = 0
sub.dataFather = Father Data, ((Father)sub).dataFather = Father Data, (sub).dataSon = Son Data
上一篇: 分析器错误消息: 未能加载类型
下一篇: Java中静态方法不具有多态性