【问题标题】:'this' Keyword is not accessing Intended variable it should. Why?'this' 关键字没有访问它应该访问的预期变量。为什么?
【发布时间】: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


【解决方案1】:

您在覆盖方法概念和变量阴影之间感到困惑,因为动态绑定将在运行时调用子类方法,但如果是“this”引用变量,它不会覆盖父变量,即使您在孩子中有相同的名称变量。

【讨论】:

  • 正确的术语是 hiding (JLS §8.3)。 ShadowingJLS §6.4.1] 是指更紧密范围内的变量阻止访问外部范围内的变量,并且不涉及继承。
  • 我明白你在这里的意思,但为了便于阅读,可能会稍微改写一下。我认为 RealSkeptics 的评论更容易理解。
  • 谢谢 :) 我会进一步了解它。上帝保佑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多