Tuesday, 31 July 2018

Constructor

       The Constructor is similar to method except constructor must have the same name as class name and it must not return any type. By default, every class have constructor whether we have declared or not. It is called when we create object using new keyword. for ex. A a = new A(). Constructor are used to initialize the objects. There are two types of constructor.
       i. Default Constructor
       ii. Parameterized Constructor.

Example of Default Constructor :

class XYZ{  
XYZ(){
System.out.println("XYZ is created");
}  
public static void main(String args[]){  
XYZ b=new XYZ();  
}  
}

Example of Parameterized Constructor :

class XYZ{  
    int id;  
    String name;  
      
    XYZ(int i,String n){  
    id = i;  
    name = n;  
    }  
    void show(){
System.out.println(id+" "+name);
   }  
   
    public static void main(String args[]){  
    XYZ x1 = new XYZ(1,"Mangesh");  
    XYZ x2 = new XYZ(2,"Harish");  
    x1.show();  
    x2.show();  
   } 
}  

No comments:

Post a Comment