DEV Community

Kesavarthini
Kesavarthini

Posted on

Constructors in Java

When creating an object in Java, we often want to initialize values at the time of object creation.

This is done using a constructor.

🔹 What Is a Constructor?

A constructor is a special method in Java that is automatically called when an object is created.

🔹 Key Points

  • Constructor name is same as class name
  • It does not have a return type
  • Used to initialize objects
  • Called using the new keyword

🔹 Why Do We Need a Constructor?

  • To initialize data members
  • To assign default values
  • To ensure object is created in a valid state

🔹 Types of Constructors in Java

1️⃣ Default Constructor

A constructor with no parameters is called a default constructor.

class Student {
    Student() {
        System.out.println("Default constructor called");
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
    }
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Parameterized Constructor

A constructor that accepts parameters is called a parameterized constructor.

class Student {
    String name;
    int age;

    Student(String n, int a) {
        name = n;
        age = a;
    }

    void display() {
        System.out.println(name + " " + age);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Constructor Overloading

Having multiple constructors in the same class with different parameters is called constructor overloading.

class Student {
    Student() {
        System.out.println("Default");
    }

    Student(String name) {
        System.out.println("Name: " + name);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Rules of Constructor

  • Constructor name must match class name
  • Constructors cannot be inherited
  • Can be overloaded
  • If no constructor is defined, Java provides a default constructor

🔹 this Keyword in Java

  • The this keyword in Java is used to refer to the current object of a class.
  • It is mainly used when instance variables and constructor parameters have the same name.

🔹 Why Do We Use this Keyword?

  • To avoid confusion between instance variables and local variables
  • To refer to the current object
  • To call another constructor in the same class

🔹 Using this to Differentiate Variables
Example:

public class Bank {




        int accountNo;
        String name;
        int balance;

        Bank(int accountNo, String name , int balance)
        {
        this.accountNo = accountNo;
        this.name = name;
        this.balance = balance;
        }

        public static void main(String[] args)
        {

        Bank accholder = new Bank(101,"kumar",1000);
        System.out.println(accholder.accountNo);//101

        Bank accholder1 = new Bank(102,"hari",1000);
        System.out.println(accholder1.accountNo); //102


        }





    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)