メソッド内でthis
キーワードを使用して、親クラスのメソッドを使用して子クラスの変数にアクセスしようとしています。メソッドが子オブジェクトによって呼び出されたときに子の値を出力しません。代わりに、そのメソッドが子のオブジェクトによって呼び出されたとしても、親クラスの値を出力しています。'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-->[email protected]
[email protected]
9
[email protected]
1
b-->[email protected]
[email protected]
9
フィールドを上書きすることはできず、フィールドを非表示にすることはできません。つまり、フィールドを参照している親のコードは、常にその子のフィールドではなく、親のフィールドにアクセスします。 – RealSkeptic
ヒント:私たちがあなたを助けるために時間を費やすことを望みます。だからあなたはできるだけ簡単にそれを作る。 「プレビュー」機能を使用して始めることで、ソースコードがまともで読みやすい方法でフォーマットされていることを確認できます。それ以外に。私は本当にあなたの質問を理解していない。 – GhostCat