Constructors in Java

📘 Java 👁 54 views 📅 Dec 01, 2025
⏱ Estimated reading time: 2 min

In Java, a constructor is a special method used to initialize objects. It is called automatically when an object is created. Constructors help in setting initial values for the object’s attributes.


1. Key Features of Constructors

  • A constructor has the same name as the class.

  • It does not have a return type, not even void.

  • It is called automatically when an object is instantiated.

  • Every class has a default constructor if none is defined explicitly.


2. Types of Constructors

(a) Default Constructor

A constructor without parameters. Java provides a default constructor if none is defined.

class Student { String name; int age; Student() { // Default constructor name = "Unknown"; age = 0; } void display() { System.out.println("Name: " + name + ", Age: " + age); } } public class Test { public static void main(String[] args) { Student s1 = new Student(); s1.display(); // Output: Name: Unknown, Age: 0 } }

(b) Parameterized Constructor

A constructor that accepts parameters to initialize an object with specific values.

class Student { String name; int age; Student(String n, int a) { // Parameterized constructor name = n; age = a; } void display() { System.out.println("Name: " + name + ", Age: " + age); } } public class Test { public static void main(String[] args) { Student s1 = new Student("John", 20); s1.display(); // Output: Name: John, Age: 20 } }

3. Constructor Overloading

Java allows multiple constructors in a class with different parameter lists. This is called constructor overloading.

class Student { String name; int age; Student() { name = "Unknown"; age = 0; } Student(String n) { name = n; age = 18; } Student(String n, int a) { name = n; age = a; } }

4. Key Points

  • Constructors cannot be inherited.

  • Can call other constructors in the same class using this().

  • Used to initialize objects efficiently.


5. Conclusion

Constructors in Java are special methods that initialize objects. They can be default or parameterized, and Java supports constructor overloading. Proper use of constructors ensures that objects start with valid and meaningful values, making programs more reliable and easier to maintain.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes