Constructors in Java

It is widely used for constructing the value of data members (instance variables) of the class.

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object.

Rules for creating Java constructor

There are two rules defined for the constructor.

a) Constructor name must be the same as its class name

b) A Constructor must have no explicit return type

Note: A Java constructor cannot be abstract, static, final, and synchronized

Types of Constructor:

There are two types of constructors in Java: constructor without argument, and parameterized constructor.

1. Constructor without argument

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

class_name()

{

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

//Java Program to create and call a default constructor 

class Bike

//creating a default constructor 

Bike()

{

System.out.println("Bike is created");

public static void main(String args[])

{ 

Bike b=new Bike (); //calling a default constructor 

}

2. Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that has two parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor. 

class Student{ 

    int id; 

    String name; 

    //creating a parameterized constructor 

    Student(int i,String n){ 

    id = i;  //constructing the value of data members of the class.

    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 

    Student s1 = new Student4(111,"Karan"); 

    Student s2 = new Student4(222,"Aryan"); 

    //calling method to display the values of object 

    s1.display(); 

    s2.display(); 

   } 


Output:

111 Karan

222 Aryan

 

When is a Constructor called?

Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

No comments:

Post a comment

All about journals and research paper | What is impact factor? | how the impact factor is calculated? | who calculate the impact factor? Scopous journals

Figure 1: One of my Research Papers When the Scholars are in their Master or PhD or in any research field. They are supposed to writ...