2016-08-01 10 views
0

メソッド内で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 
+5

フィールドを上書きすることはできず、フィールドを非表示にすることはできません。つまり、フィールドを参照している親のコードは、常にその子のフィールドではなく、親のフィールドにアクセスします。 – RealSkeptic

+0

ヒント:私たちがあなたを助けるために時間を費やすことを望みます。だからあなたはできるだけ簡単にそれを作る。 「プレビュー」機能を使用して始めることで、ソースコードがまともで読みやすい方法でフォーマットされていることを確認できます。それ以外に。私は本当にあなたの質問を理解していない。 – GhostCat

答えて

1

、これは変数の 'this'参照の場合には当てはまりません。子変数に同じ名前の変数があっても、親変数を上書きしません。

+0

正しい用語は*非表示*です([JLS§8.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3))。 * Shadowing *([JLS§6.4.1](http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.4.1)]は、 – RealSkeptic

+0

ここであなたの言うことを理解していますが、読みやすくするために少し言い直すことができます。RealSkepticsのコメントははるかに理解しやすいと思います。 – Drgabble

+0

ありがとうございます:)私はさらにそれを見ていきます。神のご加護を –

関連する問題