This is a compile problem. There is no method getX
who receives a int
as a parameter in the class MyPoint
.
However, this makes sense, because getters have no parameters. The idea of this code seems to be to define which is the center and not to discover which is. In other words, you should call the Setter (setX
), and not the getter (getX)
. Notice that with the Y, you do it right and call the getter (getY
). I mean, 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, you’ll still get one NullPointerException
because you can’t call the Setter of the object center
when there is no object yet center
. 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 still one more question to consider. Note that the MyCircle
is constructed by means of constructor parameters while the constructor MyPoint
is built by means of setters. The constructor’s parameter-based approach often produces code that is easier to move, easier to understand, simpler, smaller, and less likely to produce unpleasant surprises. So let’s change the approach of MyPoint
to use the constructor’s parameter-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;
}
}
getX
andsetY
are static? If not, you have to instantiateMyPoint
– Valdeir Psr
Couldn’t create center and assign center values in the constructor? (learning java yet ,n I got to look Static )
– Adlprog
If possible click on [Edit] and put the error, it is easier to understand.
– Valdeir Psr
I put the error that is shown.
– Adlprog