Intro of JAVA
Learn Java
A constructor is special type of method that is used to initialize the object.It is block similar to method having same name as that of class name. it execute automatically as soon as object is created
Following is syntax of constructor:
class classname{
classname(){ //constructor
}
}
There are two types of Java constructor:
Default constructor is also known as no-argument constructor.Default constructor does't have any parameter value.It is created by compiler and it provide default values i.e null or 0 depend upon data types.
Syntax:
classname(){}
Example:
class Simpleconstructor{
//creating default constructor
Simpleconstructor(){
}
public static void main(String[]args){
//calling default constructor
Simpleconstructor sim=new Simpleconstructor();
System.out.println("Example of default const");}
};
Output:
A constructor which has specific number of character is called parameterized constructor and it is defined by user.With help of this type of constructor we can initialize object with unique value.
Example:
class Perimeter{
int id;
String name;
//creating a parameterized constructor
Perimeter(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Perimeter s1 = new Perimeter(1,"Chetan");
Perimeter s2 = new Perimeter(2,"Chetna");
//calling method to display the values of object
s1.display();
s2.display();
}
};
Output: