Constructor in java
Constructor in java
Constructors are used to initialize the object’s state.It is called when the instance of class is created.
It is special type of method which is used to intialize the object.Every time when object is created using new() keyword at least one constructor is called and memory is allocated to the object of the class.
If there are no constructor then java compiler provide default constructor.
- Class Name and constructor name must be same.
- Constructor does not have any return type.
- Java constructor can not be abstract, static, final, and synchronized.
Types of constructor
There are two types of constructor
1.Default Constructor
2.Parameterized Constructor
1.Default Constructor:A constructor that does not have any parameter is called default constructor.
Syntax:
Class_Name(){}
Example of default constructor in java:
Class Demo
{
Demo() //default constructor is created
{
System.out.println("constructor is called");
}
public static void main()
{
Demo demo=new Demo();// calling a default constructor
}
}2.Parameterized Constructor:A constructor that have special number of parameters is called parameterized constructor. It can have any number of parameters in constructor i.e Syntax:
Class_Name(int a){}
Example of Parameterised Constructor:
Class Demo
{
Demo(String name) //Parameterized constructor is created
{
System.out.println("name is::"+" "+name);
}
public static void main()
{
Demo demo=new Demo("kk");// calling a default constructor
}
}
Comments
Post a Comment