user3569452
user3569452

Reputation: 59

How to simplify similar constructors?

How can I simplify this:

Is it necessary to have two different constructors with just one little difference.

Is there a way to simplify that using just one of them?

public class MyCostructor {

    public MyCostructor(int w, int h, String name) {
         this.w = w;
         this.h = h;
         this.name = name;
    }
    
    public MyCostructor(int w, int h) {
         this.w = w;
         this.h = h;
    }
}

Upvotes: 3

Views: 503

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Use this() in your constructor:

public MyCostructor(int w, int h, String name) {
    this(w, h);
    this.name = name;
}

public MyCostructor(int w, int h) {
    this.w = w;
    this.h = h;
}

Upvotes: 3

Alexis C.
Alexis C.

Reputation: 93842

Yes you can use the keyword this to call another constructor and you respect the DRY principle (don't repeat yourself).

public MyCostructor(int w, int h){ 
   this(w,h,null);
}

You can read more here (section Using this with a Constructor)

Upvotes: 6

Related Questions