Constructor

constructor in Java is a block of code similar to a method that’s called when an instance of an object is created.

  • A constructor doesn’t have a return type.
  • The name of the constructor must be the same as the name of the class.
  • Unlike methods, constructors are not considered members of a class.
  • A constructor is called automatically when a new instance of an object is created.

Format of Constructor

 public ClassName (parameter-list) [throws exception...]
 {
 statements...
   }   
  • The public keyword indicates that other classes can access the constructor. 
  • ClassName must be the same as the name of the class that contains the constructor.
  • Notice also that a constructor can throw exceptions if it encounters situations that it can’t recover from.
  • Everytime an object is created using new() keyword, atleast one constructor is called. It is called a default constructor.
  • It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Types of Constructor

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Default constructor

Java Compiler adds a default constructor to your class, only when you don't type any constructor in your class.

But if you do type a constructor in your class, you are not supplied a default no-arg constructor by the compiler.

  • Default constructor is always a no-argument constructor, i.e. it accepts no arguments.
  • The access modifier of default constructor is same as access modifier of the class. For example - if a class is public and if you haven't typed in any constructor for your class, compiler will supply a public no-argument default constructor.

 

Example

 class DefaultConstructorExample{
  int uid;
  String name;
  void display(){
  System.out.println(uid+" "+name);
  }
  public static void main(String args[]){
  DefaultConstructorExample o1=new DefaultConstructorExample();
  o1.display();
  }
  }

Output

 0 null

Explanation

In the above class “DefaultConstructor”, you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor, which are displayed as output. Default constructor is used to provide the default values to the object like 0, null etc. depending on the datatype of the variable.

 

Parameterized Constructor

  • A constructor having parameter is called parameterized constructor.
  • Parameterized constructor can have any number of parameters. You can overload parameterized constructor as well.

  Example

 class Student4{
  int id;
  String name;
  Student4(int i,String n){
  id = i; 
  name = n;
 }
 void display(){
 System.out.println(id+" "+name);
 }
 public static void main(String args[]){
 Student4 s1 = new Student4(100,"Rohit");
 Student4 s2 = new Student4(200,"Amit");  
 s1.display();
 s2.display();
}
}

Output

 100 Rohit
 200 Amit