Error with constructor

-4
MyCircle c = new MyCircle(2,5,8);/// Instanciei um objeto no main.
public class MyCircle {

    private MyPoint center; 
    private int radius=1;

    public MyCircle(int x,int y,int radius) {

       this.center.getX(x); ///na classe MyPoint ha a variável x e y com os respectivos gets e sets
       this.center.setY(y);
       this.radius = radius;

    }
    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: questao.MyPoint.getX
    at questao.MyCircle.<init>(MyCircle.java:17)
    at questao.Questao.main(Questao.java:27)
C:\Users\M\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)
    
asked by anonymous 11.05.2018 / 04:21

1 answer

2

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;
    }
}
    
11.05.2018 / 06:11