简体   繁体   中英

Passing an object through a method via it's constructor in Java?

I'm trying to pass the String label into my method toString() from the constructors String of the same name. However, I keep getting an error telling me that label cannot be resolved to a variable. Here's my code:

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 + "]";
    }


}

I've been able to infer that it has something to do with the body of the constructor, but I can't figure out what. Thank you.

You need to store the label variable within your LabeledPoint class:

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() + "]";
    }
}

Edit: applied suggestions from @Stephen P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM