Constructor in Java

Constructor allows programmer to create an object of class.This can also be called as creating an instance. Constructor  looks like methods but it's not.Constructor does not have any return type and name of the constructor must be same as class name.Constructor is invoked implicitly,if you don’t write a constructor in your class, java would generate one default constructor.Constrcutors can not be override.

Types of Constructor:

  • Default Constructor.
  • Parameterized Constructor.

\star Default Constructor: The constructor which does not have any arguments and no body.

Example:

public Demo() {
}

\star Parameterized Constructor: The Constructor which is having arguments is know as Parameterized Constructor.

Example:

public Demo(int a, int b){
 System.out.println("This is Parameterized Constructor");    
}

 

Posted on by