Wednesday, 1 January 2014

Constructors

Constructors:
  • Constructor is a special type of method that is used to initialize the object.
  • They method has the same name as that of class.
  • They do not have any return type not even void.
  • They are called or invoked when an object of class is created and can't be called explicitly.
  • They can be overloaded and are parameterized.
  • Attributes of an object may be available when creating objects if no attribute is available then default constructor is called.
  • It is optional to write constructor method in a class but due to their utility they are used. If no constructor is written default constructor is invoked  implicitly.
Example of default constructor: 
     
class Bike{  
  
Bike(){System.out.println("Bike is created");}  
  
public static void main(String args[]){  
Bike b=new Bike();  
}  
}  

Output: Bike is created

Example of parameterized constructor:

class Student{  
    int id;  
    String name;  
      
    Student(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student s1 = new Student(111,"Karan");  
    Student s2 = new Student(222,"Aryan");  
    s1.display();  
    s2.display();  
   }  
}  

Output: 111 Karan
             222 Aryan
 
Example of constructor overloading:
 
class Student{  
    int id;  
    String name;  
    int age;  
    Student(int i,String n){  
    id = i;  
    name = n;  
    }  
    Student(int i,String n,int a){  
    id = i;  
    name = n;  
    age=a;  
    }  
    void display(){System.out.println(id+" "+name+" "+age);}  
   
    public static void main(String args[]){  
    Student s1 = new Student(111,"Karan");  
    Student s2 = new Student(222,"Aryan",25);  
    s1.display();  
    s2.display();  
   }  
}  

Output: 111 Karan 0
             222 Aryan 25

 

No comments:

Post a Comment