Programming Tutorials

Constructor Overloading in Java

By: aathishankaran in Java Tutorials on 2007-03-08  

In addition to overloading normal methods, you can also overload constructor methods. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception. To understand why, we can take example for this below program.

class Box {
    double width;
    double height;
    double depth;

    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    double volume() {
        return width * height * depth;
    }
}

As you can see, the Box() constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box() constructor. For example, the following statement is currently invalid:

Box ob = new Box();

Since Box() requires three arguments, it's an error to call it without them. This raises some important questions. What if you simply wanted a box and did not care ( or know) what its initial dimensions were? Or, what if you want to be able to initialize a cube by specifying only one value that would be used for all three dimensions? As the Box class is currently written, these other options are not available to you.

Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it handles the situations just described. Here is a program that contains an improved version of Box that does just that:

class Box {
    double width;
    double height;
    double depth;

    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    Box() {
        width = -1;
        height = -1;
        depth = -1;
    }

    Box(double len) {
        width = height = depth = len;
    }

    double volume() {
        return width * height * depth;
    }
}

class OverloadCons {
    public static void main(String args[]) {
        Box mybox1 = new Box(10, 20, 15);
        Box mybox2 = new Box();
        Box mycube = new Box(7);
        double vol;
        vol = mybox1.volume();
        System.out.println("Volume of mybox1 is" + vol);
        vol = mybox2.volume();
        System.out.println("Volume of mybox2 is" + vol);
        vol = mycube.volume();
        System.out.println("Volume of mycube is" + vol);
    }
}

The output produced by this program is shown here:

Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mybox1 is 343.0

As you can see, the proper overloaded constructor is called based upon the parameters specified when new is executed.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)