What is Constructor in Java: Simple Explanation and Example
constructor is a special method used to create and initialize objects of a class. It has the same name as the class and no return type. When you create a new object, the constructor runs automatically to set up the object.How It Works
Think of a constructor like a recipe for making a cake. When you want a cake (an object), you follow the recipe (constructor) to prepare it with the right ingredients (initial values). In Java, the constructor is a special method that runs automatically when you create a new object using the new keyword.
The constructor has the same name as the class and does not return any value, not even void. Its job is to set up the new object’s initial state, like setting default values or using values you provide. If you don’t write a constructor, Java gives you a default one that does nothing special.
Example
This example shows a simple class Car with a constructor that sets the car's brand and year when a new car object is created.
public class Car { String brand; int year; // Constructor public Car(String brand, int year) { this.brand = brand; this.year = year; } public void displayInfo() { System.out.println("Brand: " + brand + ", Year: " + year); } public static void main(String[] args) { Car myCar = new Car("Toyota", 2020); myCar.displayInfo(); } }
When to Use
Use constructors whenever you want to create objects with specific starting values. For example, if you have a class representing a person, you can use a constructor to set their name and age right when you create the person object.
Constructors help keep your code clean and organized by ensuring every object starts with the right data. They are especially useful in real-world programs where objects need to be set up properly before use, like setting up a bank account with an initial balance or creating a game character with certain skills.
Key Points
- A constructor has the same name as the class and no return type.
- It runs automatically when you create a new object with
new. - Constructors initialize objects with starting values.
- If no constructor is written, Java provides a default one.
- You can have multiple constructors with different parameters (called constructor overloading).