gpt4 book ai didi

java - 使用关键字 'this'

转载 作者:行者123 更新时间:2023-12-01 18:48:03 25 4
gpt4 key购买 nike

我正在努力理解如何准确地计算出在父类(super class)构造函数中使用“this”时所指的内容。

我有三门课:

     public class Animal {

public int x;

public Animal() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}

public String toString() {
return "Animal";
}
}

public class Mammal extends Animal{

public int x;

public Mammal() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}

public String toString() {
return "Mammal";
}

}

public class Dog extends Mammal{
public int x;

public Dog() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}

public String toString() {
return "Dog " + x;
}

public static void main(String[] args) {
Dog rover = new Dog();
}

}

调用Dog构造函数的结果是:

狗 01

狗 01

狗11

因此,当我在 Animal 构造函数中调用 this.toString() 时, this 指的是漫游者(狗)。但是当我在 Animal 构造函数中执行 this.x++ 时,它会增加 Animal 中的 x,而不是 Dog 中的 x。

这是正确的吗?为什么 this.x++ 不增加流动站的 x?

最佳答案

通过在 Animal 的子类中声明变量 x,您实际上是在遮蔽 Animal 的变量 x,因此 Mammal 中的 this.x 引用 Mammal 中的 x,它遮蔽了 Animal 的 x。当然,在 Animal 构造函数中,x 引用 Animal 中的 x,因为 Animal 类不知道任何子类。

我不知道你为什么要隐藏 x,删除 Animal 的所有子类中的 public int x 应该会导致你期望的行为。 Animal 的所有子类都将引用 Animal 中声明的 x。

有关阴影的更多详细信息,请参见此处: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15

希望能帮上忙

关于java - 使用关键字 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872468/

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