This is a compile problem. There is no getX
method that receives int
as a parameter in class MyPoint
.
However, this makes sense, since getters have no parameters. The idea of this code seems to be to define what the center is and not find out what it is. In other words, you should call the setter ( setX
), not the getter ( getX)
.) Note that with Y, you do it right and getter ( getY
). That is, what you wanted was this:
public class MyCircle {
private MyPoint center;
private int radius;
public MyCircle(int x, int y, int radius) {
this.center.setX(x);
this.center.setY(y);
this.radius = radius;
}
}
But even if you fix this problem, it will still give NullPointerException
because you can not call the setter of the center
object when there is still no center
object. The solution is this:
public class MyCircle {
private MyPoint center;
private int radius;
public MyCircle(int x, int y, int radius) {
this.center = new MyPoint();
this.center.setX(x);
this.center.setY(y);
this.radius = radius;
}
}
public class MyPoint {
private int x;
private int y;
public MyPoint() {
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
However, there is one more question to consider. Note that MyCircle
is built through constructor parameters while MyPoint
is built using setters . The builder-based approach typically produces easier-to-move, easier to understand, simpler, smaller, and less prone to unpleasant surprises. So let's change the MyPoint
approach to using the constructor-based approach:
public class MyCircle {
private MyPoint center;
private int radius;
public MyCircle(int x, int y, int radius) {
this.center = new MyPoint(x, y);
this.radius = radius;
}
}
public class MyPoint {
private int x;
private int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
}