Sushant19
Sushant19

Reputation: 21

Problems in writing Constructors

(first time practice after studying OOP concepts. Go little easy in the answers)

(I am just following instructions from a test-your-skills homework; that's why I am not discussing logics of other classes and files)

I have to add 3 constructors in a single class which is itself extended from a parent class.

First constructor uses the same parameters of the constructor from parent class.

Second and third constructor keep adding parameters respectively.

I am confused about syntax of the body of 2nd and 3rd constructors.

public class House 
   extends Building {

// TODO - Put your code here.
private String mOwner;
private boolean mPool;

//This constructor exists in Building class. So, I can use it here with super keyword. Right?
public House(int length, int width, int lotLength, int lotWidth){
    super(length, width, lotLength, lotWidth);
}

//Is using "this" keyword okay here? I am just using the constructor existing in this file.
public House(int length, int width, int lotLength, int lotWidth, String Owner){
    this(length, width, lotLength, lotWidth);
    mOwner = Owner;
}

// Is this right?
public House(int length, int width, int lotLength, int lotWidth, String Owner, boolean pool){
    this(length, width, lotLength, lotWidth, Owner);
    mPool = pool;
}

}

Upvotes: 0

Views: 44

Answers (1)

JoeChris
JoeChris

Reputation: 231

This concept is called constructor chaining

Like the idea is what if we wanted to initialize a building and we didn't know if we wanted it to have a pool yet? If our constructor for this class requires us to enter us a value for boolean pool, we could run into problems.

So constructor chaining is useful because we would still be able to initialize a building without knowing all of the information yet.

we would just use this constructor if we didn't know if we wanted a pool:

public House(int length, int width, int lotLength, int lotWidth, String Owner)

Everything you wrote is fine. The this() calls are fine. If you're still unclear -- https://beginnersbook.com/2013/12/java-constructor-chaining-with-example/

Upvotes: 1

Related Questions