Constructor in Java – Explained with Examples
A constructor in Java is a special method used to initialize objects. It shares the same name as the class and has no return type. This tutorial explains the basics of constructors and covers constructor overloading in Java with real examples.
Watch: Java Constructor & Constructor Overloading (YouTube)
What is a Constructor?
- A constructor is automatically called when an object is created.
- It has the same name as the class.
- It does not have a return type (not even
void
).
Example: Product Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Product { int id; String title; double price; // Default Constructor Product() { System.out.println("Default constructor called"); } // Parameterized Constructor Product(int id, String title, double price) { this.id = id; this.title = title; this.price = price; } } |
In the above example this.id refers to the instance variable while only id refers to the parameter in the constructor
Constructor Overloading
Constructor overloading means creating multiple constructors in the same class with different parameter lists. This allows you to create objects in different ways.
Constructor vs Method in Java
Constructor | Method |
---|---|
Same name as class | Can have any name |
No return type | Must have a return type |
Called automatically | Called explicitly |
Used to initialize object | Used to perform actions |
Summary
- Java supports constructor overloading via different parameter types/count.
- No return type — not even
void
. - Used to initialize objects with or without parameters.
Interview Tip:
Overloading is always based on parameters, not return type.
- Java does not allow two constructors with the same parameter list even if the return type is different.
- Be prepared to explain the flow of constructor invocation.
Need more help understanding this? Connect with online Java tutor for private tutoring or training.
Leave a Reply