Java constructors or constructors in Java is a terminology been used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object.
example 1:
class PE{
String tshirt;
int size;
public PE(String shirt)
{
tshirt=shirt;
System.out.println(“shirt”+shirt);
}
public PE(String shirt,int S)
{
tshirt=tshirt;
size=size;
System.out.println(“shirt”+shirt+”\n”+S);
}
public static void main(String args[])
{
PE o=new PE(“abc”);
PE k=new PE(“abs”,24);
System.out.println(k.tshirt);
System.out.println(k.size);
}
}
output
shirtabc
shirtabs
24
null
0
example2:
class collage{
String name;
int stuid;
boolean pass;
public collage(String N, int ID)
{
String name=”N”;
stuid=ID;
System.out.println(“name “+N+”\n”+ID);
}
public collage(String N, int ID,boolean T)
{
String name=”N”;
stuid=ID;
pass=T;
System.out.println(“name “+N+”\n”+ID+”\n”+T);
}
public static void main(String args[])
{
collage s=new collage(“sobhika”,123);
collage p=new collage(“ramya”,456,true);
}
}
output;
name sobhika
123
name ramya
456
true
refrence id: