3

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;
    }
}
peterh
  • 11,875
  • 18
  • 85
  • 108
user3569452
  • 49
  • 1
  • 6

2 Answers2

6

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)

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
3

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;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 2
    usual practice is to call `this()` from constructor with less arguments – Iłya Bursov Apr 24 '14 at 15:22
  • @Lashane yes, but in this case there's no need to set `this.name = null;` since that's the default value. Besides, IMO sending `null` as parameter is not quite right (even if it does the right job), do you? – Luiggi Mendoza Apr 24 '14 at 15:23
  • @Luiggi Mendoza so you mean it is not possible to do everything with only one constructor, right? I mean.. **in a game** I want to create a car with a yellow dot in the front and another equal car without the dot, two constructors are necessary in that case? – user3569452 Apr 24 '14 at 15:29
  • @user3569452 sadly, yes. You can only simplify the way you implement the constructors using `this()` as the first line of the constructor. – Luiggi Mendoza Apr 24 '14 at 15:30
  • @user3569452 it is depends on your class structure, you can define "dot" as optional attribute and just provide getters/setters for it, also take look at builders and chaining http://stackoverflow.com/questions/17171012/how-to-avoid-constructor-code-redundancy-in-java – Iłya Bursov Apr 24 '14 at 15:31