DEV Community

R.Shobika CSE
R.Shobika CSE

Posted on

Constructor in Java

Constructor:

  • Constructor in java is a special member that is called when the object is created.

  • constructor name should be in same class name

  • It is used to set a default value to the object.

In all Java file there is a default constructor when the object is created
Eg:

class Super{
String pro_name;
int price;
public Super(String pro_name,int price){ -----> constructor
this.pro_name=pro_name;
this.price=price;
}
public static void main(String[] args){
Super pro1=new Super("boost",250); -------> Object creation
Super pro2=new Super("soap",200);----------> Object creation
System.out.println(pro1.pro_name);
System.out.println(pro1.price);
System.out.println(pro2.pro_name);
System.out.println(pro2.price);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:
boost
250
soap
200

In the above program this operator refers to current object

TYPES OF CONSTRUCTOR:

  • Default constructor
    If we doesnot create any constructor in a class the java automatically take a default constructor

  • Argument constructor
    when the object is created with some argument and pass the arguments to the constructor means is a argument constructor

  • No argument constructor
    when the object is created with no argument means is a no argument constructor

same constructor name with different number of arguments /different type(data type ) of argument is called constructor overloading.

Top comments (0)