Search code examples
javaconstructor-overloading

Constructor overloading, how do i proceed?


In my assignment we are practicing constructor overloading (on paper). I have to implement these 3 constructors (fill out) and the main constructor has to generate a circle with the coordinates (0,0) and a radius of 1. I already tried to implement the first two constructors, but don't know what to do in the third constructor. As always thank you guys for your help.

public class Center
{
    public double x;
    public double y;
}

public class Circle
{
    private Center c;
    private double radius;

    public Circle()
    {
        this(0, 0, 1); //TO-DO
    }

    public Circle(Center c, double radius)
    {
        this(0, 0, radius); //TO-DO
    }

    public Circle(double x, double y, double radius)
    {
        //TO-DO
    }
}

Solution

  • You have to assign the values to the respective variables here:

    public Circle(double x, double y, double radius) {
        this.c = new Center();
        this.c.x = x;
        this.c.y = y;
        this.radius = radius;
    }
    

    And your second constructor should be like:

    public Circle(Center c, double radius){
        this(c.x,c.y,radius); 
    }