gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:37:56 25 4
gpt4 key购买 nike

我正在尝试使用方法内的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com