Friday 25 November 2016

CONSTRUCTORS IN JAVA

Constructor is a special type of method in a class that is used initialise an object, that is a constructor is called automatically when an object of a class is created.A constructor is mainly used to initiallise the values to the variables in the functions.
The constructor has some special  properties that are:
  •     Constructor cannot have any return type ,not even void.
  • The name of the constructor should be same as the class name.

The most common types of constructors in Java programming are:
Default constructor and
Parameterised constructor


Default constructor:

Any constructor that donot take any arguments or parameters is called as the default constructor.Even is a constructor is not created in a class ,the compiler will automatically create a default constructor at the time of object creation.The default constructor mainly assigns default value to the variables.
For Example:
Here we are creating default constructor in class cars .
Class Cars
{
cars()
{
System.out.println("This is a default constructor");
}
public static void main(String args[])
{
Cars c1=new Cars();
}
}

Parameterised constructor:
Any constructor that can take parameters is called as parameterised constructor.A parameterised constructor assigns values to the distinct objects based on the type.We can have any number of parameters in a constructor.
For Example:
Here we have created constructor of student class that takes two arguments.
  1. class Student{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student(int i,String n){  
  6.     id = i;  
  7.     name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student s1 = new Student(1,"Aditya");  
    Student s2 = new Student(2"Pankaj");  
    s1.display();  
    s2.display();  
   }  
}  


No comments:

Post a Comment