Search code examples
javaconstructorcompiler-errorsgettersetter

Two constructors?


I already did my assignment with setters and getters (I did this with OOD) however I still don't understand what's the purpose of the two Rectangle methods and if ever I remove the empty Rectangle an error will prompt:

enter image description here

P.S. This is not the full code.

// private double length = 25.0;
private double width = 15.5;

public Rectangle(){

}

public Rectangle(double length, double width){
    this.length = length;
    this.width = width;
}

public void setDimension(double length,double width){
    this.length = length;
    this.width=width;
}

public double getLength(){
    return length;
}

public double getWidth(){
    return width;
}

public double area(){
    return length * width;
}

public double perimeter(){
    return 2 * (length + width);
}

public static void print(){
    Rectangle rt = new Rectangle();
    Box box = new Box();
    System.out.println("The rectangle has a length of " + rt.getLength() + " and a width of " + rt.getWidth() );
    System.out.println("The rectangle has an area of "+ rt.area());
    System.out.println("The rectangle has a perimeter of "+ rt.perimeter());
    box.print();
}

Solution

  • That's the default (no-arg) constructor. Since you have another constructor, Java will not implicitly create it if you don't define it explicitly. Since the first line in your print method calls it, you'll get an error if you remove it.