Constructor Overloading (Using Multiple Constructors) in Java

Something that is very simple to do in Java but not super intuitive is to use multiple constructors that build on each other. Suppose you have a class called Baby, and sometimes you want to specify both eye color and hair color while other times you want to specify only eye color (and use a default for hair color because you don’t know it yet). You could create two constructors to do this. The key is to use the this keyword to allow one constructor to build on the other rather than duplicating code.

public class Baby
{
  public String EyeColor;
  public String HairColor;
 
  public Baby(String eyeColor)
  {
    this(eyeColor, "Purple");
  }
 
  public Baby(String eyeColor, String hairColor)
  {
    EyeColor = eyeColor;
    HairColor = hairColor;
  }
}

11 Responses to “Constructor Overloading (Using Multiple Constructors) in Java”

  1. Is this sample code correct? Can you have two methods with the same name? and shouldn’t this:
    ” this(eyeColor, “Purple”);”
    be
    ” this(hairColor, “Purple”);”

    I am new to Java and I was noticing the redundancy in a statement like:
    Baby myBaby = new Baby(…)

    I realized that the first Baby was the class and the second was the constructor and that you could have more then one constructor. My Google of multiple constructors found your page but the code makes little sense to me. When I call the constructor called “Baby” how does it know which one to use? Is it based on position in the code?

    Thanks in advance.
    Dave

  2. Oh never mind I get it. I was reading it as “this(eyeColor = “Purple”);”” but of course it’s the first constructor is just calling the second and passing the inputted value and a default value.

    So is it automatically choosing the constructor based on how many parameters where passed?

  3. Yes, it automatically selects which constructor based on the number of parameters but also on the types of the parameters. So you could have two constructed with three parameters, as long as the parameter object types weren’t exactly the same.

  4. That’s pretty flexible, thanks for the reply.

  5. Excellent, just the information I was looking for…!

  6. very good information about this concept

  7. can u please define dynamic constructors?

  8. kinder, in what context did you hear about dynamic constructors?

  9. actually i am a student of MCA-1.my C++ lecturer has assigned me a presentation on constructors, multiple constructors and dynamic constructors are a part of it.i have never heard of dynamic constructors before. so i was confused about it. can u please help me with this topic?

  10. I’m not too familiar with C++, but here’s an explanation on Java (http://wiki.answers.com/Q/What_is_dynamic_constructor). If that doesn’t help, maybe you can find an answer in a book.

  11. this is what i was looking ,thank you

Leave a Reply