Constructors in Java

🧠 What is a Constructor?

A constructor in Java is a special method that is automatically called when an object is created. Its main purpose is to initialize objects.

A constructor has the same name as the class and doesn’t have a return type, not even void.


βœ… Syntax:

class ClassName {
ClassName() {
// constructor body
}
}

πŸ”Έ Types of Constructors:

  1. Default Constructor – No parameters.

  2. Parameterized Constructor – Takes arguments.

  3. Copy Constructor (not built-in like C++, but can be created manually).


πŸ§ͺ Example of Default Constructor:

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

public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Constructor is automatically called
}
}


πŸ§ͺ Parameterized Constructor Example:

class Student {
String name;
int age;

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

void display() {
System.out.println(name + " is " + age + " years old.");
}
}


πŸ” Constructor Overloading:

Java allows multiple constructors with different parameters:

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

πŸ“Œ Key Points:

  • A constructor is invoked automatically when the object is created.

  • No return type.

  • Can be overloaded.

  • Used for initializing objects easily.

Related Posts