父类的引用变量能够保存其对象引用及其子对象引用。 在Java中,默认情况下方法是虚拟的(参见 这 详细信息)。 非方法成员呢。例如,预测以下Java程序的输出。
null
JAVA
// A Java program to demonstrate that non-method // members are accessed according to reference // type (Unlike methods which are accessed according // to the referred object) class Parent { int value = 1000 ; Parent() { System.out.println( "Parent Constructor" ); } } class Child extends Parent { int value = 10 ; Child() { System.out.println( "Child Constructor" ); } } // Driver class class Test { public static void main(String[] args) { Child obj= new Child(); System.out.println( "Reference of Child Type :" + obj.value); // Note that doing "Parent par = new Child()" // would produce same result Parent par = obj; // Par holding obj will access the value // variable of parent class System.out.println( "Reference of Parent Type : " + par.value); } } |
输出:
Parent ConstructorChild ConstructorReference of Child Type : 10Reference of Parent Type : 1000
如果父引用变量持有子类的引用,并且父类和子类中都有“value”变量,则无论是否持有子类对象引用,它都将引用父类“value”变量。持有子类对象引用的引用将无法访问子类的成员(函数或变量)。这是因为父引用变量只能访问父类中的字段。因此,引用变量的类型决定将调用哪个版本的“值”,而不是被实例化的对象的类型。这是因为编译器只对方法使用特殊的运行时多态机制。(在这里,被实例化的对象的类型决定了要调用的方法的版本)。 可以使用带有类型转换的父指针访问子数据成员。请看最后一个例子 这 完整的代码。 本文由 闪烁泰吉 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END