top of page

Constructors in Java

  • Writer: Keshari Abeysinghe
    Keshari Abeysinghe
  • Jul 21, 2020
  • 3 min read

Constructors are required to create objects for a class. Constructor is a block of code similar to method and special type of method which is used to initialize the object.When call to the constructors ,memory for the object is allocated in the memory by JVM.

There are two types of constructors

  1. Default constructors .

  2. Parameterized constructors.

Default constructors

If user does not define a constructor the compiler creates a default constructor.default constructors do not contain any parameters.The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.In this example, we are creating the no-arg constructor in the class. It will be called at the time of object creation.

Following code snippet for the java program to create and call a default constructor


class Student{
Student()// default constructor
{
System.out.println("Hey! I am john);

}

public static void main(String []args) //main method
{
 Student student= new Student();//calling default constructors 
}

}

Expected Output

Hey! I am john



Parameterized constructors

It is used to pass the parameters when creating the objects .we can overload the

constructors by different datatypes as its parameters .

this() and super () used to in order to communicate from one constructors to

another constructors in same class and communicate with the super class constructors .

If we define only parameterized constructors, then we cannot create an object with default constructor. This is because compiler will not create default constructor. You need to create default constructor explicitly.

Following code snippet for the java program to create and call a default constructor

class Student{
int age;
String name;
char grade;

student(int a,String n, char c)//parameterized constructor
{
this.age=a;
this.name=n;
this.grade=c;

System.out.println(name+" "+age+" "+grade);

}

public static void name(Strings []args)
{
Student student=new Student(11,"john",A);//called to the constructor with parameters

}

}

Expected Output

john 11 A

There are two rules defined for the constructor.


1.Constructor name must be the same as its class name

2.A Constructor must have no explicit return type

3.A Java constructor cannot be abstract, static, final, and synchronized


We can use access modifiers such as public ,private,default and protected.


Constructors overloading

Java allows to multiple constructors, that means java can use more than one constructors .We call it constructors overloading .Here java uses different parameters to perform different tasks.The compiler differentiate constructors by the number of parameters and the data types.



class Student{
int age;
int marks;
String name;
String subject;
char grade;

student(int a,String n, char c)//parameterized constructor
{
this.age=a;
this.name=n;
this.grade=c;

System.out.println(name+" "+age+" "+grade);

}

student(int m,String s)
{
this.subject=s;
this.marks=m;
System.out.println(subject+" "+marks);
}

public static void name(Strings []args)
{
Student student1=new Student(11,"john",A);//called to the constructor with parameters
Student student2=new Student(45,"java");

}

}

Expected Output


john 11 A
java 45

Java constructor chaining


In the java we can call another constructor in same class by another constructor, using this () keyword.

this() should be the first line in the constructor.

Below example shows code for constructor chaining.


class Constructorchain{

constructorchain()
{
System.out.println("John is 18 years old");
}

constructorchain(int k){
this()
System.out.println("Kate is "+k+"years old");
}

constructorchain(int k,int j)
{
this(k);
System.out.println("Same is"+k+"and Jonee is"+j+"years old");
}

Public static void main(String []args)
{
Constructorchain chain= new Constructorchain(12,34);
}

}

Extpected Output

John is 18 years old
Kate is 12 years old
Same is 12 and Jonee is 34 years old

Singlton class using private constructors


We can make constructor as private. So that We can not create an object outside of the class.

This property is useful to create singleton class in java.

Singleton pattern helps us to keep only one instance of a class at any time.

The purpose of singleton is to control object creation by keeping private constructor.

We will learn singleton class in-detail with future lessons about design patterns .


Copying value using constructors

In java we can copy values from one objects to another object using constructors .

There are many ways to copy the values of one object into another in Java. They are:


  1. By constructor

  2. By assigning the values of one object into another

  3. By clone() method of Object class


Following code snippet about how to copy the values of one object into another using Java constructors.



class Copy_values{
int a,b ;

copy_values(int x, int y)// initializing the integer variables of the 
{                            class
this.a=x;
this.b=y;
}

copy_values(Copy_values c)//initializing another object
{
this.a=c.a;
this.b=c.b
}

printfunction()
{
System.out.print(a+" , "+b);
}

public static void main(String []args)
{
Copy_values c1= new  Copy_values(10,56);
Copy_values c2= new  Copy_values(c1);
c1.printfunction();
c2.printfunction();
}

}

Expected Output

10 , 56
10 , 56

Difference between constructors and methods in Java


ree

Constructor class

Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package.

Comments


Subscribe Form

Thanks for submitting!

©2020 by Quick Code. Proudly created with Wix.com

bottom of page