How do I use a specific variable of an object that is in another class?

Tom :

I'm trying to modify the toString method. I have an object called 'p' which has 2 doubles as attributes, in this case, 5.0 and 6.0 which are 'x' and 'y' values, respectively.

The brackets, inside the String converter "< Point >", should be printing the "x" of p, the "y" of p, while in the circle it should print the radius. Sure enough printing the radius works, but I'm unsure as to how I'm supposed to specify "x" of p and "y" of p.

Class Circle:

package packageName;

public class Circle {

public Point center;
public double radius;

public Circle(Point a, double b) {
    this.center = a;
    this.radius = b;
}

    public String toString() {
        String converter = "<Circle(<Point(" + (x of p) + ", " + (y of p) + ")>, " + this.radius + ")>";
        return converter;
    }


    public static void main(String args []) {
        Point p = new Point(5.0, 6.0);
        Circle c = new Circle(p, 4.0);
        c.toString();
    }
}  

Class Point:

package packageName;
public class Point{


public double x;
public double y;

public Point(double x, double y) {
    this.x = x;
    this.y = y;
}

public String toString() {
    String input = "<Point(" + this.x + ", " + this.y + ")>";
    return input;

  }
}
Sweeper :

You are saying that you want to print "x" of "p" and "y" of "p" in the toString method of Cirlce, but toString does not know anything about p because p is declared locally in the main method.

In the main method, you created p and passed it to the first parameter of Circle, which then gets assigned to center. So center stores the same thing as p. You should use center.x and center.y:

String converter = "<Circle(<Point(" + center,x + ", " + center.y + ")>, " + this.radius + ")>";
return converter;

Alternatively, you could call center.toString() directly:

String converter = "<Circle(" + c.toString() + ", " + this.radius + ")>";
return converter;

Notice how I used the syntax foo.bar to mean "bar of foo". This is dot notation, and it seems like you are unfamiliar with this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161094&siteId=1
Recommended