0% found this document useful (0 votes)
3 views

Computer Constructor

Uploaded by

bindaladwit19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Computer Constructor

Uploaded by

bindaladwit19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

CONSTRUCTOR in JAVA

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.

// Example of parameterized constructor


class cons
{
int rno;
double mks;
cons(int r1,double m1) // parameterized constructor
{
rno=r1;
mks=m1;
}
}

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
}
}

// program based on parameterized constructor


class paracons
{
int rno;
String nm;
double mks;
paracons(int r1,String n1,double m1) // parameterized constructor
{
rno=r1;
nm=n1;
mks=m1;
}
public void disp()
{
System.out.println(rno+"\t"+nm+"\t"+mks);
}
public static void main()
{
paracons obj=new paracons(20,”raju”,99.0); // constructor is invoked implicitly
obj.disp(); // explicitly called by user
}
}

You might also like