Constructor

Published: (February 14, 2026 at 02:23 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Constructor

  • The constructor name must be the same as the class name.
  • A constructor is a special method used to initialize instance variables when an object is created.
  • When an object is instantiated, the constructor runs automatically; it cannot be called manually.
  • In Java, constructors are defined using the class name (no return type).

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 accHolder1 = new Bank(101, "kumar", 1000);
        System.out.println(accHolder1.accountNo); // 101

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

Purpose of Constructor

  • The this keyword refers to the current object.
  • Inside a constructor, this is used to assign values to instance variables, distinguishing them from parameters or local variables.

Constructor Overloading

Constructor overloading means defining multiple constructors with different parameter lists.

public class Payilagam {
    String name;
    String email;
    String password;

    // Constructor with name, email, and password
    Payilagam(String name, String email, String password) {
        this.name = name;
        this.email = email;
        this.password = password;
    }

    // Constructor with only email and password
    Payilagam(String email, String password) {
        this.email = email;
        this.password = password;
    }

    public static void main(String[] args) {
        Payilagam user2 = new Payilagam("abc.com", "kumar@123");
        System.out.println(user2);
    }
}
0 views
Back to Blog

Related posts

Read more »

Python OOP for Java Developers

Converting a Simple Java Square Class to Python Below is a step‑by‑step conversion of a basic Square class written in Java into an equivalent Python implementa...

Access Modifiers in Java

markdown !Nanthini Ammuhttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2...

Module-01--Interview Question _JAVA

1. How many data types are in Java? - Primitive Data Types 8 total: byte, short, int, long, float, double, char, boolean - Non‑Primitive Reference Data Types:...