6

I am very new to Java and trying to learn the subject, having previous programming exposure in only HTML/CSS. I have started with Herbert Schildt and progressed through a few pages.

I am unable to understand the exact advantages of Constructor Overloading. Isn't it easier to Overload Methods using single constructor for flexibility? Moreover if I am trying to use constructor overloading to use one object to initialize another, there are simpler ways to do it! So what are the benefits and in which situation should I use Constructor Overloading.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
S. Chatterjee
  • 61
  • 1
  • 1
  • 4
  • Is Schildt's reputation any good when it comes to Java? I remember him basically being a laughingstock when he tried to write books about C and C++... – cHao Aug 26 '13 at 13:02
  • Schildt's Java book is good..dont know about the C and C++ ones. This Java book starts from the very basic. So for someone, who is new to OOP and Java its really enlightening. – S. Chatterjee Sep 04 '13 at 11:27

6 Answers6

5

Constructor overloading is very useful for simulate default values, or to construct an object from an already existing instance (copy)
Here is an example:

public class Color {

    public int  R, G, B, A;

    // base ctr
    public Color(int R, int G, int B, int A) {
        this.R = R;
        this.G = G;
        this.B = B;
        this.A = A;
    }

    // base, default alpha=255 (opaque) 
    public Color(int R, int G, int B) {
        this(R, G, B, 255);
    }

    // ctr from double values
    public Color(double R, double G, double B, double A) {
        this((int) (R * 255), (int) (G * 255), (int) (B * 255), (int) (A * 255));
    }

    // copy ctr
    public Color(Color c) {
        this(c.R, c.G, c.B, c.A);
    }

}

Here, the first constructor is very simple. You specify R,G,B & Alpha value for a color.

While this is enough to use the Color class, you provide a second constructor, liter, which auto assign 255 to alpha if not specified by the user.

The third ctr shows that you can instantiate your Color object with double between 0. and 1. instead of integers.

The last one takes an Color as unique argument, it copies the given object.

The benefits lies also in the fact that the first constructor is always called, and you can use that to manually count your instances. Let say you have a private static int count=0 attribute, you can track the number of Color instance like this:

    // base ctr
    public Color(int R, int G, int B, int A) {
        this.R = R;
        this.G = G;
        this.B = B;
        this.A = A;
        ++count;
    }

countis incremented from any constructor.

johan d
  • 2,798
  • 18
  • 26
2

Considering the simplest example of constructor overloading :

Class A
{
int a;

A()
{
this.a = 0;
}

A(int a)
{
this.a = a;
}

} // end class

Advantage: Now I may simply need to use the default constructor new A() to assign default values or for a more dynamic case specify what value it must be new A(10) which is a parametrised constructor. do read this question

Isn't it easier to Overload Methods using single constructor for flexibility?

Job of constructor is to instantiate the object , and the job of the method is to process the object values. Thus limiting methods to processing (exception to setter methods) and constructor to creation of object will help in a long run and also make your class more usable to your team-mates

Moreover if I am trying to use constructor overloading to use one object to initialize another, there are simpler ways to do it!

alternative is initializer , also read

Community
  • 1
  • 1
Srinath Ganesh
  • 2,496
  • 2
  • 30
  • 60
1

When you are dealing with immutable classes and you want to provide multiple ways to instantiate them, then overloading the constructor is convenient.

proskor
  • 1,382
  • 9
  • 21
  • 1
    You *could* do it with multiple factory methods delegating to a single constructor. But that would probably be cheating ;-) – Joachim Sauer Aug 26 '13 at 12:45
1

It depends completely on how you are constructing your object.

One of Classical example of Constructor overloading is ArrayList in Java. ArrayList has three constructors one is empty, other takes a collection object and one take initial Capacity. these overloaded constructor allows flexibility while create arraylist object. It may be possible that you don't know size of arraylist during creation than you can simply use default no argument constructor but if you know size then its best to use overloaded Constructor which takes capacity. Since ArrayList can also be created from another Collection, may be from another List than having another overloaded constructor makes lot of sense. By using overloaded constructor you can converty your ArrayList into Set or any other collection.

More info with general examples.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

The way the constructor is defined will make sure that the parameters of the constructor will be passed to the object upon instantiation.

Overloading a method won't "force" anyone to call it unlike having parameters in the constructor, where you can't instanciate an object without passing those paremeters.

Having multiple way to construct an object might be useful, like with the Color class, in ndj's answer, can be created in four different ways. Each way makes sure that Color as the minimum informations to be useful, or "work".

Those informations could be missing if Color only had a contructor without parameter and, for the class to "work", would be to call setRand the other methods... which don't exist in the Color class .

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
0

You may have several variables in a class... But you want to initialize only few(one or two) variables at the time of object creation. So in this case Its always better to have overloaded constructors so that you can call respective constructor depends on your requirement. One thing you should remember always,.. while overloading constructors always provide a default constructor(Zero argument constructor).Even with empty implementation.

user2714918
  • 327
  • 1
  • 3
  • 10
  • 1
    There is no need to **always** provide a default constructor. – proskor Aug 26 '13 at 13:13
  • It might also not be **wanted** to provide a default constructor. – Jonathan Drapeau Aug 26 '13 at 13:24
  • If there is no default constructor.. and you class been extended by another class.. for example say ur class is A which doesn't have a default constructor..Class B extends A... While creating the object of class B.. If you say B b= new B(); then what will happen? – user2714918 Aug 26 '13 at 13:28
  • It depends on the implementation of the constructor of B. If A does not have a default constructor, then it's up to the constructor of B to call the appropriate constructor of its superclass. – proskor Aug 26 '13 at 13:32