Skip to content

Q 24 - Constructor Overload #28

Discussion options

You must be logged in to vote

🤓 Yes, a constructor can be overloaded in Java.

🔁 Constructor Overloading in Java

Constructor overloading means defining multiple constructors in the same class, each with a different parameter list.

✅ Why Overload Constructors?

  • To allow different ways of initializing an object.
  • To provide flexibility based on available data.

🧪 Example

class Book {
    String title;
    int pages;

    // Default constructor
    Book() {
        title = "Unknown";
        pages = 0;
    }

    // Constructor with one parameter
    Book(String t) {
        title = t;
        pages = 100;
    }

    // Constructor with two parameters
    Book(String t, int p) {
        title = t;
        pages = p;
    }
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by AmjustGettingStarted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants