'this'关键字不会访问它应该的预期变量。为什么?

时间:2016-08-01 08:24:10

标签: java inheritance 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-->PackageName.C@15db9742
PackageName.C@15db9742
9
PackageName.C@6d06d69c
1
b-->PackageName.B@7852e922
PackageName.B@7852e922
9

1 个答案:

答案 0 :(得分:1)

您在重写方法概念与变量的阴影之间会感到困惑,因为动态绑定会在运行时调用子类方法,但在'这种情况下,情况并非如此。即使你在child中有相同的名字变量,变量的引用也不会覆盖父变量。