【问题标题】:Passing an object through a method via it's constructor in Java?通过Java中的构造函数通过方法传递对象?
【发布时间】:2019-10-03 22:21:52
【问题描述】:

我正在尝试将字符串label 从同名的构造函数字符串传递到我的方法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 + "]";
    }


}

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

【问题讨论】:

  • 您的班级没有名为 label 的成员。你的构造函数也不对字符串做任何事情
  • 您的toString() 方法不可能理解label 所指的变量。
  • 如何将label 从构造函数传递到方法中?
  • 你没有。您需要将传递给构造函数的值存储在某处,然后在toString() 中使用它。您不能将值直接从构造函数传递给toString(),因为您没有从构造函数调用toString()

标签: java methods constructor


【解决方案1】:

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

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 的建议

【讨论】:

  • 有几件事……我会把它改成private final String label,除非你想改变它;在这种情况下,它将是private String label(你应该几乎总是使用private)并且你需要public LabeledPoint setLabel(final String newLabel) { this.label = newLabel; return this; }(我在setter中返回this,以便它们可以被链接)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
相关资源
最近更新 更多