How would you use constructor overloading in Java? Provide an example

date:2024-06-05 12:30:48 author:admin browse: View comments Add Collection

How would you use constructor overloading in Java? Provide an example

How would you use constructor overloading in Java? Provide an example.

Constructor overloading in Java is a technique where multiple constructors are defined with different parameters. It allows objects to be initialized in various ways, enhancing flexibility and readability.

Consider an example of a ‘Book’ class:

public class Book {
    String title;
    int pages;
    // Constructor 1
    public Book(String t) {
        this.title = t;
    }
    // Constructor 2
    public Book(String t, int p) {
        this.title = t;
        this.pages = p;
    }
}
In the above code, two constructors are overloaded. The first constructor initializes only the book’s title while the second also includes the number of pages. This way, we can create a ‘Book’ object either by just providing the title or both the title and page count.

支付宝转账赞助

支付宝扫一扫赞助

微信转账赞助

微信扫一扫赞助