Html & Html5

The World's best Software Development Study Portal

Java Constructor

A constructor is special type of method that is used to initialize the object.It is block similar to method having same name as that of class name. it execute automatically as soon as object is created

Rules for creating Constructor:

  • Constructor name must be same as its class name
  • Constructor must have no explicit return type not even void.
  • the only modifier applicable for constructor are public,private,default,protected.

Way to call constructor

Following is syntax of constructor:

class classname{

classname(){ //constructor



Types of Constructor:

There are two types of Java constructor:

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

Java Default Constructor

Default constructor is also known as no-argument constructor.Default constructor does't have any parameter value.It is created by compiler and it provide default values i.e null or 0 depend upon data types.




class Simpleconstructor{

//creating default constructor



public static void main(String[]args){

//calling default constructor

Simpleconstructor sim=new Simpleconstructor();

System.out.println("Example of default const");}



Java Parameterized Constructor

A constructor which has specific number of character is called parameterized constructor and it is defined by user.With help of this type of constructor we can initialize object with unique value.


class Perimeter{

int id;

String name;

//creating a parameterized constructor

Perimeter(int i,String n){

id = i;

name = n;


//method to display the values

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

Perimeter s1 = new Perimeter(1,"Chetan");

Perimeter s2 = new Perimeter(2,"Chetna");

//calling method to display the values of object