Constructors are nothing but member methods of a class, whose task is to initialize the instance variable of a class with some initial values. Its speciality begins, it shares the name of the class.
Rules:
- A member method which shares the name of the class.
- Constructors are used just for initializing the instance variables of a class.
- They never return any kind of values, even “void”.
- They automatically invoked upon the creation of an object.
- They can be parameterized.
- They are not inherited.
Constructors can be classified into the following two…
- Constructors without arguments.
- Constructors with arguments.
Constructors without arguments:
class Box
{
private double width;
private double height;
private double depth;
Box()
{
width=10;
height=20;
depth=30;
}
public void compute()
{
double vol=width*height*depth;
System.out.println("The volume of the box is : "+vol);
}
}
class App22
{
public static void main(String yck[])
{
Box b1=new Box();
b1.compute();
}
}
output:
\>javac App22.java
\>java App22
The volume of the box is : 6000.0
Constructors with arguments: The problem with the above constructor is that any number of objects you create would be initialized with the same set of values. To initialize different objects with different set’s of values you can design a parameterized constructor. A parameterized constructor is nothing but constructor with arguments.
Syntax: class_name object_name = new constructor(arguments);
class Box
{
private double width;
private double height;
private double depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
public void compute()
{
double vol=width*height*depth;
System.out.println("The volume of the box is : "+vol);
}
}
class App23
{
public static void main(String yck[])
{
Box b1=new Box(10,20,30);
b1.compute();
Box b2=new Box(5,6,7);
b2.compute();
}
}
output:
\>javac App23.java
\>java App23
The volume of the box is : 6000.0
The volume of the box is : 210.0
Constructors overloading:
class Box
{
private double width;
private double height;
private double depth;
Box()
{
width=10;
height=20;
depth=30;
}
Box(double l)
{
width=height=depth=l;
}
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
Box(Box ob)
{
width=ob.width;
height=ob.height;
depth=ob.depth;
}
void compute()
{
double vol=width*height*depth;
System.out.println("The volume of the box is : "+vol);
}
}
class App24
{
public static void main(String yck[])
{
Box b1=new Box();
b1.compute();
Box b2=new Box(5);
b2.compute();
Box b3=new Box(10,10,10);
b3.compute();
Box b4=new Box(b1);
b4.compute();
}
}
output:
\>javac App24.java
\>java App24
The volume of the box is : 6000.0
The volume of the box is : 125.0
The volume of the box is : 1000.0
The volume of the box is : 6000.0
