Computer Constructor
Computer Constructor
1) A constructor is a member function with the same name as that of its class.
Calc obj = new Calc( );
2) It is used to initialize the objects of that class type with legal initial value.
3) Constructor is automatically/implicitly called while creating an object.
4) For constructor return type specification is not needed (Not even void)
5) Access specifier of a constructor is always public
6) We can invoke constructor only once for a given object.
7) We can also use a constructor to perform any other tasks.(like input/calculation/display etc.)
8) Java also supports constructor overloading.
9) A constructor cannot be used as static modifier.
10) Java supports 3 types of constructors
a) Default constructor(with out arguments )
b) Parameterized constructor (with argument(s) )
c) Copy constructor (With object as an argument(s))
Default constructor is used/invoked without any parameter, it is used to store legal values (or the values
specified) in data members.
// Example of default constructor
class defcons
{
int rno;
String nm;
double mks;
defcons() // default /simple constructor
{
rno=10;
nm="Ramu";
mks=90.5;
}
}
Parameterized constructor is used/invoked with a list of primitive data type values as parameters , it is
used to assign the received parameter values to data members.
1
// program based on default constructor
class defcons
{
int rno;
String nm;
double mks;
defcons() // default /simple constructor
{
rno=10;
nm="Ramu";
mks=90.5;
}
public void disp()
{
System.out.println(rno+"\t"+nm+"\t"+mks);
}
public static void main()
{
defcons obj=new defcons(); // constructor is invoked implicitly
obj.disp(); // explicitly called by user
}
}