Java Constructors

Special methods that initialize objects

🏗️ What are Constructors?

Constructors are special methods that initialize objects when they are created. They set up initial values for attributes and prepare the object for use, running automatically when you use the 'new' keyword.


class Person {
    String name;
    int age;
    
    // Constructor
    public Person(String n, int a) {
        name = n;
        age = a;
    }
}
                                    

Types of Constructors

🔧

Default

No parameters, basic setup

public Person() {
    name = "Unknown";
}
⚙️

Parameterized

Takes parameters for custom setup

public Person(String n, int a) {
    name = n; age = a;
}
📋

Copy

Creates copy of another object

public Person(Person other) {
    name = other.name;
}
🔄

Overloaded

Multiple constructors in one class

public Person() { }
public Person(String n) { }

🔹 Default Constructor

A constructor with no parameters that sets up basic default values:

// Book.java
class Book {
    String title;
    String author;
    int pages;
    double price;
    boolean isAvailable;
    
    // Default constructor
    public Book() {
        title = "Untitled";
        author = "Unknown Author";
        pages = 0;
        price = 0.0;
        isAvailable = true;
        System.out.println("New book created with default values");
    }
    
    // Method to display book info
    public void displayInfo() {
        System.out.println("=== Book Information ===");
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.println("Pages: " + pages);
        System.out.println("Price: $" + price);
        System.out.println("Available: " + isAvailable);
    }
}

// BookExample.java
public class BookExample {
    public static void main(String[] args) {
        // Using default constructor
        Book book1 = new Book();
        book1.displayInfo();
        
        // Modify attributes after creation
        book1.title = "Java Programming";
        book1.author = "John Smith";
        book1.pages = 350;
        book1.price = 29.99;
        
        System.out.println("\nAfter modification:");
        book1.displayInfo();
    }
}

Output:

New book created with default values
=== Book Information ===
Title: Untitled
Author: Unknown Author
Pages: 0
Price: $0.0
Available: true

After modification:
=== Book Information ===
Title: Java Programming
Author: John Smith
Pages: 350
Price: $29.99
Available: true

🔹 Parameterized Constructor

A constructor that accepts parameters to initialize attributes with specific values:

// Student.java
class Student {
    String name;
    int studentId;
    String major;
    double gpa;
    int year;
    
    // Parameterized constructor
    public Student(String studentName, int id, String studentMajor, double studentGpa, int academicYear) {
        name = studentName;
        studentId = id;
        major = studentMajor;
        gpa = studentGpa;
        year = academicYear;
        System.out.println("Student " + name + " has been enrolled!");
    }
    
    // Method to display student info
    public void displayStudent() {
        System.out.println("=== Student Profile ===");
        System.out.println("Name: " + name);
        System.out.println("ID: " + studentId);
        System.out.println("Major: " + major);
        System.out.println("GPA: " + gpa);
        System.out.println("Year: " + year);
    }
    
    // Method to update GPA
    public void updateGPA(double newGpa) {
        gpa = newGpa;
        System.out.println(name + "'s GPA updated to: " + gpa);
    }
}

// StudentExample.java
public class StudentExample {
    public static void main(String[] args) {
        // Creating students with parameterized constructor
        Student student1 = new Student("Emma Wilson", 12345, "Computer Science", 3.8, 2);
        Student student2 = new Student("Michael Brown", 12346, "Mathematics", 3.6, 3);
        Student student3 = new Student("Sarah Davis", 12347, "Physics", 3.9, 1);
        
        // Display all students
        student1.displayStudent();
        System.out.println();
        
        student2.displayStudent();
        System.out.println();
        
        student3.displayStudent();
        System.out.println();
        
        // Update a student's GPA
        student1.updateGPA(3.9);
    }
}

Output:

Student Emma Wilson has been enrolled!
Student Michael Brown has been enrolled!
Student Sarah Davis has been enrolled!
=== Student Profile ===
Name: Emma Wilson
ID: 12345
Major: Computer Science
GPA: 3.8
Year: 2

=== Student Profile ===
Name: Michael Brown
ID: 12346
Major: Mathematics
GPA: 3.6
Year: 3

=== Student Profile ===
Name: Sarah Davis
ID: 12347
Major: Physics
GPA: 3.9
Year: 1

Emma Wilson's GPA updated to: 3.9

🔹 Constructor Overloading

You can have multiple constructors with different parameters in the same class:

// Car.java
class Car {
    String brand;
    String model;
    int year;
    String color;
    double price;
    
    // Default constructor
    public Car() {
        brand = "Unknown";
        model = "Unknown";
        year = 2023;
        color = "White";
        price = 0.0;
        System.out.println("Default car created");
    }
    
    // Constructor with brand and model
    public Car(String carBrand, String carModel) {
        brand = carBrand;
        model = carModel;
        year = 2023;
        color = "White";
        price = 0.0;
        System.out.println("Car created: " + brand + " " + model);
    }
    
    // Constructor with brand, model, and year
    public Car(String carBrand, String carModel, int carYear) {
        brand = carBrand;
        model = carModel;
        year = carYear;
        color = "White";
        price = 0.0;
        System.out.println("Car created: " + year + " " + brand + " " + model);
    }
    
    // Constructor with all parameters
    public Car(String carBrand, String carModel, int carYear, String carColor, double carPrice) {
        brand = carBrand;
        model = carModel;
        year = carYear;
        color = carColor;
        price = carPrice;
        System.out.println("Full car details set: " + year + " " + color + " " + brand + " " + model);
    }
    
    // Method to display car info
    public void displayCar() {
        System.out.println("=== Car Details ===");
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Color: " + color);
        System.out.println("Price: $" + price);
        System.out.println();
    }
}

// CarExample.java
public class CarExample {
    public static void main(String[] args) {
        // Using different constructors
        Car car1 = new Car();
        Car car2 = new Car("Toyota", "Camry");
        Car car3 = new Car("Honda", "Civic", 2022);
        Car car4 = new Car("BMW", "X5", 2024, "Black", 65000.0);
        
        // Display all cars
        car1.displayCar();
        car2.displayCar();
        car3.displayCar();
        car4.displayCar();
    }
}

Output:

Default car created
Car created: Toyota Camry
Car created: 2022 Honda Civic
Full car details set: 2024 Black BMW X5
=== Car Details ===
Brand: Unknown
Model: Unknown
Year: 2023
Color: White
Price: $0.0

=== Car Details ===
Brand: Toyota
Model: Camry
Year: 2023
Color: White
Price: $0.0

=== Car Details ===
Brand: Honda
Model: Civic
Year: 2022
Color: White
Price: $0.0

=== Car Details ===
Brand: BMW
Model: X5
Year: 2024
Color: Black
Price: $65000.0

🔹 Copy Constructor

A constructor that creates a new object by copying another object:

// Rectangle.java
class Rectangle {
    double length;
    double width;
    String color;
    
    // Regular constructor
    public Rectangle(double l, double w, String c) {
        length = l;
        width = w;
        color = c;
        System.out.println("New rectangle created: " + length + "x" + width + " (" + color + ")");
    }
    
    // Copy constructor
    public Rectangle(Rectangle other) {
        length = other.length;
        width = other.width;
        color = other.color;
        System.out.println("Rectangle copied: " + length + "x" + width + " (" + color + ")");
    }
    
    // Method to calculate area
    public double getArea() {
        return length * width;
    }
    
    // Method to display rectangle info
    public void displayInfo() {
        System.out.println("Rectangle: " + length + "x" + width + " (" + color + ")");
        System.out.println("Area: " + getArea());
        System.out.println();
    }
    
    // Method to modify dimensions
    public void resize(double newLength, double newWidth) {
        length = newLength;
        width = newWidth;
        System.out.println("Rectangle resized to: " + length + "x" + width);
    }
}

// RectangleExample.java
public class RectangleExample {
    public static void main(String[] args) {
        // Create original rectangle
        Rectangle original = new Rectangle(5.0, 3.0, "Blue");
        original.displayInfo();
        
        // Create copy of original
        Rectangle copy = new Rectangle(original);
        copy.displayInfo();
        
        // Modify the copy
        copy.resize(7.0, 4.0);
        copy.displayInfo();
        
        // Original remains unchanged
        System.out.println("Original rectangle after copy was modified:");
        original.displayInfo();
    }
}

Output:

New rectangle created: 5.0x3.0 (Blue)
Rectangle: 5.0x3.0 (Blue)
Area: 15.0

Rectangle copied: 5.0x3.0 (Blue)
Rectangle: 5.0x3.0 (Blue)
Area: 15.0

Rectangle resized to: 7.0x4.0
Rectangle: 7.0x4.0 (Blue)
Area: 28.0

Original rectangle after copy was modified:
Rectangle: 5.0x3.0 (Blue)
Area: 15.0

🔹 Constructor Rules

Important Rules:

  • Same name: Constructor must have same name as class
  • No return type: Constructors don't have return types (not even void)
  • Automatic call: Called automatically when object is created
  • Can be overloaded: Multiple constructors with different parameters

Best Practices:

  • Initialize all important attributes
  • Validate parameter values
  • Provide default constructor when needed
  • Use meaningful parameter names
  • Keep constructors simple and focused

🧠 Test Your Knowledge

What is special about a constructor's name?