Java Constructors Overloading

Ram Pothuraju
This Simple Java Program is for performing Constructor Overloading in Java. 

Constructor is required when we declare a class object. Java Class Constructors initializes the variables of the object. Constructor Overloading is done so that the objects of different forms can be initialized at the declaration time.

The Below program uses a class named Box which finds the volume of the Box object. This class has 2 constructors one for initializing a Cube Box and other for Initializing a Rectangular Box.
As those are constructors and return nothing, they dont have a return type.


class Box
{
int l,b,h;
Box(int x)             // Constructor for Cube
{
 l=x;
 b=x;
 h=x;
}
Box(int x,int y,int z)            //Constructor for Rectangle
{
 l=x;
 b=y;
 h=z;
}
void volume()
{
          System.out.println("Volume of the box is "+(l*b*h));
}
public static void main(String args[])
{
Box cube= new Box(10);          //Calling cube constructor
Box b=new Box(10,4,7);          //Calling box constructor
cube.volume();
b.volume();
}
}

Tags

Post a Comment

0Comments

Post a Comment (0)