gpt4 book ai didi

java - 在 Java 中通过构造函数传递一个对象?

转载 作者:行者123 更新时间:2023-12-02 09:27:38 25 4
gpt4 key购买 nike

我试图将字符串 label 从同名的构造函数 String 传递到我的方法 toString() 中。但是,我不断收到错误消息,告诉我 label 无法解析为变量。这是我的代码:

public class LabeledPoint extends java.awt.Point {

LabeledPoint(int x, int y, String label){
setLocation(x, y);

}

public String toString() {
return getClass().getName() + "[x=" + x + ",y=" + y + ",label=" + label + "]";
}


}

我已经能够推断它与构造函数的主体有关,但我不知道是什么。谢谢。

最佳答案

您需要在 LabeledPoint 类中存储 label 变量:

public class LabeledPoint extends java.awt.Point {
private String label;
LabeledPoint(int x, int y, String label){
setLocation(x, y);
this.label = label;
}

public LabeledPoint setLabel (String final label){
this.label = label;
return this;
}

public String getLabel (){
return label;
}

public String toString() {
return getClass().getName() + "[x=" + x + ",y=" + y + ",label=" + this.getLabel() + "]";
}
}

编辑:应用了@Stephen P的建议

关于java - 在 Java 中通过构造函数传递一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58227617/

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