Course contentsShow
← Java
Lesson 320 of 2,8708. Classes and EncapsulationFree lesson

Constructor Overloading Basics

Learn that a class can have multiple constructors with different parameter lists, allowing flexible object initialization.

Constructor Overloading Basics

What you'll learn: You'll discover how a single class can provide multiple constructors to give callers flexible ways to create objects.

The Core Idea

Just like methods can be overloaded (same name, different parameters), constructors can be overloaded too. This means your class can define multiple constructors, each accepting a different set of parameters. When someone creates an object using new, Java picks the constructor that matches the arguments provided.

Think of it like ordering a coffee: you might say "small coffee," "small coffee with milk," or "small coffee with milk and sugar." Same product (coffee/object), but different levels of customization based on what information you provide.

Why Constructor Overloading?

Constructor overloading lets you initialize objects in different ways depending on what information is available or convenient at creation time. Some callers might have all the details; others might want defaults for some fields.

How It Works

You define multiple constructors in the same class, each with a different parameter list (different number or types of parameters). Java distinguishes them by their signatures:

class Book {
    String title;
    String author;
    int pages;
    
    // Constructor with all parameters
    Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    // Constructor with just title and author
    Book(String title, String author) {
        this.title = title;
        this.author = author;
        this.pages = 0; // default value
    }
    
    // Constructor with only title
    Book(String title) {
        this.title = title;
        this.author = "Unknown";
        this.pages = 0;
    }
}

Now you can create Book objects flexibly:

  • new Book("Java Basics", "Smith", 300)
  • new Book("Java Basics", "Smith")
  • new Book("Java Basics")

Key Takeaway: Constructor overloading allows a class to have multiple constructors with different parameter lists, giving object creators flexibility in how they initialize new instances.