← Back to Chapters

Java Constructors

? Java Constructors

? Quick Overview

A constructor in Java is a special method that is automatically called when an object is created. It is mainly used to initialize objects with default or custom values.

? Key Concepts

  • Constructor name must be the same as the class name
  • Constructors do not have a return type
  • They are invoked automatically when an object is created
  • Used for object initialization

? Syntax / Theory

Java provides different types of constructors based on how objects are initialized. The most common ones are default constructors and parameterized constructors.

? Code Example(s)

? View Code Example
// Class demonstrating a default constructor
class Student {
int id;
String name;

Student() {
// Default constructor initializes values
id = 1;
name = "Unknown";
}

void display() {
System.out.println(id + " " + name);
}
}

public class Main {
public static void main(String[] args) {
// Object creation triggers constructor call
Student s1 = new Student();
s1.display();
}
}
? View Code Example
// Class demonstrating a parameterized constructor
class Employee {
int empId;
String empName;

Employee(int id, String name) {
// Parameterized constructor assigns values
empId = id;
empName = name;
}

void show() {
System.out.println(empId + " " + empName);
}
}

public class Main {
public static void main(String[] args) {
// Passing values during object creation
Employee e1 = new Employee(101, "Amit");
e1.show();
}
}

?️ Interactive Demo: Car Constructor

Fill in the fields to simulate a Parameterized Constructor, or just click "Default" to see a Default Constructor in action.

// Click a button to simulate Java code execution...

? Created Object in Memory

model:
year:

? Live Output / Explanation

Output

1 Unknown
101 Amit

When an object is created, the constructor runs automatically and initializes the data members.

✅ Tips & Best Practices

  • Always initialize important variables inside constructors
  • Use parameterized constructors for flexibility
  • Keep constructor logic simple and clean
  • A class can have multiple constructors

? Try It Yourself

  • Create a class with multiple constructors
  • Try constructor overloading
  • Print a message inside a constructor to see when it runs