【发布时间】:2016-08-01 08:24:10
【问题描述】:
我正在尝试使用方法内部的this 关键字通过父方法访问子类的变量。但是当子对象调用该方法时,它不会打印子对象的值。相反,即使子对象调用了该方法,它也会打印父类的值。
这是我的代码:
class C {
int t = 9;
void disp() {
// here 'this' shows to which object its referring.
// It showed me same as System.out.println(b) showed me
System.out.println(this);
/*
But, why this.t is printing 9,
when this method is called by 'b' reference variable,
it should print 0, because B class contains instance variable t
of its own and here this is pointing to the object of B class,
it shows 9 for 'c' and 1 for 'c1' but y not similarly 0 for 'b'
as when the method is called by 'b',
***this refers to the memory location of b but doesn't prints the value of that object***,
hows that going on???
*/
System.out.println(this.t);
}
}
class B extends C {
int t = 0;
}
class A {
public static void main(String args[]) {
C c = new C();
C c1 = new C();
B b = new B();
c1.t = 1;
System.out.println("Memory location of c-->" + c);
c.disp(); // here output is 9
c1.disp(); //here output is 1
System.out.println("Memory location of b-->" + b);
b.disp();
}
}
输出:
c-->PackageName.C@15db9742
PackageName.C@15db9742
9
PackageName.C@6d06d69c
1
b-->PackageName.B@7852e922
PackageName.B@7852e922
9
【问题讨论】:
-
您不能覆盖字段,只能隐藏它们。也就是说,任何查看字段的父代码都将始终访问父字段,而不是子字段。
-
提示:您希望我们花时间帮助您。所以你让它尽可能简单;从使用“预览”功能开始,以确保您的源代码以体面、可读的方式格式化。除此之外;我真的不明白你的问题。
标签: java inheritance this