gpt4 book ai didi

java - 调用 Java 关键字 super

转载 作者:行者123 更新时间:2023-12-02 07:49:01 26 4
gpt4 key购买 nike

我最近在一次潜在工作的测试中使用了以下代码。

class Point {
protected final int x, y;
private final String name;

Point(int x, int y) {
this.x = x;
this.y = y;
name = makeName();
}

protected String makeName() {
return "[" + x + "," + y + "]";
}

public final String toString() {
return name;
}
}

public class ColorPoint extends Point {
private final String color;

ColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}

protected String makeName() {
return super.makeName() + ": " + color;
}

public static void main(String[] args) {
System.out.println(new ColorPoint(4, 2, "purple"));
}
}

测试询问程序员想要打印什么,即 [4, 2]:紫色。它还询问实际打印出什么,即 [4: 2]: null。我想知道的是为什么。

最佳答案

在子类ColorPoint中,当调用父类(super class)Point的构造函数时,变量color的值尚未被赋值。因此,当调用 makeName() 方法时,color 实际上是 null,因此 name 变量变为 [4,2]:null,这就是您打印时看到的内容。

关于java - 调用 Java 关键字 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161093/

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