Monday 29 August 2016

Constructor in Java

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor


Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
  1. class Bike1{  
  2. Bike1(){System.out.println("Bike is created");}  
  3. public static void main(String args[]){  
  4. Bike1 b=new Bike1();  
  5. }  
  6. }  
Test it Now Output:
Bike is created 
 
 
 
 





Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.    }  
  17. }  
Test it Now Output:
111 Karan
222 Aryan

No comments:

Post a Comment