blog

Home / DeveloperSection / Blogs / Constructor in Java

Constructor in Java

Manoj Pandey2167 25-Apr-2015

Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of the class is created and can't be called explicitly.

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

For example

class Sample
{
Sample( )
{ }
}


Rules for creating java constructor

There are basically two rules defined for the constructor.

  •  The constructor name must be same as its class name.
  •  The constructor must have no explicit return type.

Types of Java constructors

There are two types of constructors:

  • Default constructor (no-arg constructor)
  • Parameterized constructor

 

Constructor in Java

 

1. Default Constructor-: A constructor that has no parameter is known as default constructor.

Example of the default constructor

classMyClas { 
     public MyClas() {
           System.out.print("Default Constructor...");
     }
}
 
class Sample {
     publicstaticvoid main(String[] args) {
           MyClasclas=newMyClas();
     }
}

 

2. Java parameterized constructor-:A constructor that have parameters is known as a parameterized constructor.

Example of parameterized constructor

class Student{  
    intid; 
    String name; 
     
    Student(int i,String n){ 
    id = i; 
    name = n; 
    } 
    void display(){System.out.println(id+" "+name);} 
  
    publicstaticvoid main(String args[]){ 
    Student s1 = new Student(111,"Zack"); 
    Student s2 = new Student(222,"James Anderson"); 
    s1.display(); 
    s2.display(); 
   } 
}

Output-:

111 Zack

222 James Anderson


Notes-: Constructor return current class instance but we cannot use return type.



Here I am creating a sample of constructor overloading

 

class Cricketer

{

 String name;

 String team;

 intage;

 Cricketer ()   //default constructor.

 {

  name ="";

  team ="";

  age = 0;

 }

 Cricketer(String n, String t, int a)   //constructor overloaded

 {

  name = n;

  team = t;

  age = a;

 }

Cricketer (Cricketer ckt)//constructor similar to copy constructor of c++

 {

  name = ckt.name;

  team = ckt.team;

  age = ckt.age;

 }

 public String toString()

 {

  return"this is " + name + " of "+team;

 }

}

 

Classtest:

{

 publicstaticvoid main (String[] args)

 {

  Cricketer c1 = new Cricketer();

  Cricketer c2 = new Cricketer("sachin", "India", 32);

  Cricketer c3 = new Cricketer(c2 );

  System.out.println(c2);

  System.out.println(c3);

  c1.name = "Virat";

  c1.team= "India";

  c1.age = 32;

  System .out. print in (c1);

 }

}

Output-:

this is sachin of india

this is sachin of india

this is virat of india


Updated 23-Feb-2018

Leave Comment

Comments

Liked By