java - “this”关键字没有访问它应该访问的预期变量。为什么?

标签 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

最佳答案

您在重写方法概念与变量遮蔽之间感到困惑,因为动态绑定(bind)将在运行时调用子类方法,但在变量的“this”引用的情况下,情况并非如此,它不会覆盖父变量,即使您在 child 中有相同名称的变量。

关于java - “this”关键字没有访问它应该访问的预期变量。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38694098/

相关文章:

php - 如何从类外部调用父方法?

java - 是否应该启用 Checkstyle 中的 RequireThis 检查?

java - 从文本文件读取的代码不起作用

java - Jetty Websocket 空闲超时

php - PHP中静态成员的继承

c++ - 从类返回引用到 this

javascript - "this"作为对象成员资格而不是事件处理程序上的节点引用?

java - 如果客户端计算机具有 java 8 并且服务器具有 openjdk 11,我的 java web start 应用程序可以工作吗?

java - spring mvc 中的任意返回类型

python - 覆盖 Django Rest 中的 authToken View