FuzzyPeanuts
FuzzyPeanuts

Reputation: 9

Chaining together constructors in java

I am trying to create a program that will tell you if you can make nothing, a line, a rectangle, or a box depending on the amount of dimensions you input. We are not allowed to use this."variable" but have to use this.("parameters") to chain constructors. The only issue I'm facing is that all but one constructor print the line in the one constructor they all chain to. Here's the code if that was confusing:

//Conner Cozine
public class OverloadedBox {

  //instance variables

  //default constructor
  public OverloadedBox(){
    this(0, 0, 0);
    System.out.println("Nothing is created");
  }
  //one parameter constructor
  public OverloadedBox(int l){
    this(l, 0, 0);
    System.out.println("A line is created");
  }
  //two parameter constructor
  public OverloadedBox(int l, int w){
    this(l, w, 0);
    System.out.println("A rectangle is created");
  }
  //three parameter constructor
  public OverloadedBox(int l, int w, int h){
    System.out.println("A box is made");

  }
}

And the test class:

public class OverloadedBoxTest {
  public static void main(String[] args){
    //OverloadedBox b = new OverloadedBox(); //nothing
    //OverloadedBox b1 = new OverloadedBox(1, 3); //rectangle
    //OverloadedBox b2 = new OverloadedBox(1, 3, 4); //box
    //OverloadedBox b3 = new OverloadedBox(2); //line
  }

}

Upvotes: 0

Views: 46

Answers (1)

dave
dave

Reputation: 11975

With the way your constructors are currently defined, I don't think you can achieve what you want. This is because the first three all call the fourth, so the output from the fourth is always printed.

You could add a fifth private constructor to achieve what you want:

public class OverloadedBox {
    //instance variables

    public OverloadedBox() {
        this(0, 0, 0, "nothing");
    }
    public OverloadedBox(int l) {
        this(l, 0, 0, "a line");
    }
    public OverloadedBox(int l, int w) {
        this(l, w, 0, "a rectangle");
    }
    public OverloadedBox(int l, int w, int h) {
        this(l, w, h, "a box");
    }
    private OverloadedBox(int l, int w, int h, String type) {
        System.out.println("Created " + type);
    }
}

Upvotes: 1

Related Questions