
Java OOP – Chapter 7: Constructors and Constructor Overloading in Java
In this lesson, you’ll learn what constructors are, how they work in Java, and how to use constructor overloading to give your classes more flexibility when creating objects.
What is a Constructor?
A constructor is a special method that’s called automatically when a new object is created. It initializes the object's state (fields/variables).
Key Points:
Constructor name must match the class name.
It has no return type (not even
void).If you don’t define one, Java provides a default constructor.
public class Person {
String name;
// Constructor
Person(String inputName) {
name = inputName;
}
void greet() {
System.out.println("Hello, my name is " + name);
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Emma");
p.greet(); // Output: Hello, my name is Emma
}
}
What is Constructor Overloading?
Constructor overloading means creating multiple constructors in the same class with different parameters.
This gives users multiple ways to create an object.
Example: Constructor Overloading
public class Car {
String brand;
int year;
// No-arg constructor
Car() {
brand = "Unknown";
year = 0;
}
// Parameterized constructor
Car(String brandName, int modelYear) {
brand = brandName;
year = modelYear;
}
void printDetails() {
System.out.println(brand + " - " + year);
}
}
Usage:
public class Main {
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("Toyota", 2022);
c1.printDetails(); // Unknown - 0
c2.printDetails(); // Toyota - 2022
}
}Constructor Chaining
Use this() to call another constructor in the same class.
class Book {
String title;
int pages;
Book() {
this("Untitled", 100); // Calls the next constructor
}
Book(String t, int p) {
title = t;
pages = p;
}
}Summary
A constructor initializes new objects.
Constructor overloading allows creating objects in different ways.
Use
this()for constructor chaining.
Assignment: Lesson 7 – Constructors and Overloading
Objective:
Practice defining constructors, overloading them, and chaining using this().
Part 1: Conceptual Questions
Answer these:
What is the role of a constructor?
What happens if you don’t define any constructor in your class?
Can a constructor have a return type?
Part 2: Coding Task
Step 1:
Create a class Book with the following:
Fields:
title(String),author(String),pages(int)Constructor 1: No-argument constructor that sets default values.
Constructor 2: Constructor with
titleandauthor.Constructor 3: Constructor with all three fields (use
this()to chain).
Step 2:
In the main() method, create 3 Book objects using each constructor and call a method printInfo() to display the details.
Github: https://github.com/tuanbeovnn/java-bootcamp/tree/java-bootcamp-oop-chapter7
