Java – Constructors

Java Constructors

Java constructors are special types of methods that are used to initialize an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your constructor, the default constructor is no longer used.

Rules for Creating Java Constructors

You must follow the below-given rules while creating Java constructors:

  • The name of the constructors must be the same as the class name.
  • Java constructors do not have a return type. Even do not use void as a return type.
  • There can be multiple constructors in the same class, this concept is known as constructor overloading.
  • The access modifiers can be used with the constructors, use if you want to change the visibility/accessibility of constructors.
  • Java provides a default constructor that is invoked during the time of object creation. If you create any type of constructor, the default constructor (provided by Java) is not invoked.

Creating a Java Constructor

To create a constructor in Java, simply write the constructor’s name (that is the same as the class name) followed by the brackets and then write the constructor’s body inside the curly braces ({}).

Syntax

Following is the syntax of a constructor −

classClassName{ClassName(){}}

Example to create a Java Constructor

The following example creates a simple constructor that will print “Hello world”.

publicclassMain{// Creating a constructorMain(){System.out.println("Hello, World!");}publicstaticvoidmain(String[] args){System.out.println("The main() method.");// Creating a class's object// that will invoke the constructorMain obj_x =newMain();}}

This program will print:

The main() method.
Hello, World!

Types of Java Constructors

There are three different types of constructors in Java, we have listed them as follows:

  • Default Constructor
  • No-Args Constructor
  • Parameterized Constructor
Java Constructors

1. Default Constructor

If you do not create any constructor in the class, Java provides a default constructor that initializes the object.

Example: Default Constructor (A Class Without Any Constructor)

In this example, there is no constructor defined by us. The default constructor is there to initialize the object.

publicclassMain{int num1;int num2;publicstaticvoidmain(String[] args){// We didn't created any structure// a default constructor will invoke hereMain obj_x =newMain();// Printing the valuesSystem.out.println("num1 : "+ obj_x.num1);System.out.println("num2 : "+ obj_x.num2);}}

Output

num1 : 0
num2 : 0

2. No-Args (No Argument) Constructor

As the name specifies, the No-argument constructor does not accept any argument. By using the No-Args constructor you can initialize the class data members and perform various activities that you want on object creation.

Example: No-Args Constructor

This example creates no-args constructor.

publicclassMain{int num1;int num2;// Creating no-args constructorMain(){
    num1 =-1;
    num2 =-1;}publicstaticvoidmain(String[] args){// no-args constructor will invokeMain obj_x =newMain();// Printing the valuesSystem.out.println("num1 : "+ obj_x.num1);System.out.println("num2 : "+ obj_x.num2);}}

Output

num1 : -1
num2 : -1

3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized constructor.

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor’s name.

Example 1: Parameterized Constructor

This example creates a parameterized constructor.

publicclassMain{int num1;int num2;// Creating parameterized constructor Main(int a,int b){
    num1 = a;
    num2 = b;}publicstaticvoidmain(String[] args){// Creating two objects by passing the values // to initialize the attributes.// parameterized constructor will invokeMain obj_x =newMain(10,20);Main obj_y =newMain(100,200);// Printing the objects valuesSystem.out.println("obj_x");System.out.println("num1 : "+ obj_x.num1);System.out.println("num2 : "+ obj_x.num2);System.out.println("obj_y");System.out.println("num1 : "+ obj_y.num1);System.out.println("num2 : "+ obj_y.num2);}}

Output

obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200

Example 2: Parameterized Constructor

Here is a simple example that uses a constructor −

// A simple constructor.classMyClass{int x;// Following is the constructorMyClass(int i ){
      x = i;}}

You would call constructor to initialize objects as follows −

publicclassConsDemo{publicstaticvoidmain(String args[]){MyClass t1 =newMyClass(10);MyClass t2 =newMyClass(20);System.out.println(t1.x +" "+ t2.x);}}

Output

10 20

Constructor Overloading in Java

Constructor overloading means multiple constructors in a class. When you have multiple constructors with different parameters listed, then it will be known as constructor overloading.

Example: Constructor Overloading

In this example, we have more than one constructor.

// Example of Java Constructor Overloading// Creating a Student ClassclassStudent{String name;int age;// no-args constructorStudent(){this.name ="Unknown";this.age =0;}// parameterized constructor having one parameterStudent(String name){this.name = name;this.age =0;}// parameterized constructor having both parametersStudent(String name,int age){this.name = name;this.age = age;}publicvoidprintDetails(){System.out.println("Name : "+this.name);System.out.println("Age : "+this.age);}}publicclassMain{publicstaticvoidmain(String[] args){Student std1 =newStudent();// invokes no-args constructorStudent std2 =newStudent("Jordan");// invokes parameterized constructorStudent std3 =newStudent("Paxton",25);// invokes parameterized constructor// Printing detailsSystem.out.println("std1...");
    std1.printDetails();System.out.println("std2...");
    std2.printDetails();System.out.println("std3...");
    std3.printDetails();}}

Output

td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *