Challenge: Constructor Delegation
Swipe to start coding
Imagine you are creating a library management system. You need to build a Book class that can be initialized in different ways using constructor delegation. Your task is to implement multiple constructors that call each other to avoid code duplication, and a method to display book information.
- Implement constructors using delegation:
- A constructor with
title,author, andyear.
- A constructor with
- A constructor with
titleandauthoronly; setsyearto0. - A constructor with
titleonly; setsauthorto"Unknown"andyearto0.
- Implement a method
printInfothat prints the book information in the format:
"Title: <title>, Author: <author>, Year: <year>"
Example
Book("1984", "George Orwell", 1949) → Title: 1984, Author: George Orwell, Year: 1949
Book("Clean Code", "Robert C. Martin") → Title: Clean Code, Author: Robert C. Martin, Year: 0
Book("Mystery Book") → Title: Mystery Book, Author: Unknown, Year: 0
Book() → Title: Undefined, Author: Unknown, Year: 0
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain this in simpler terms?
What are some examples related to this topic?
Where can I learn more about this?
Awesome!
Completion rate improved to 3.13
Challenge: Constructor Delegation
Swipe to show menu
Swipe to start coding
Imagine you are creating a library management system. You need to build a Book class that can be initialized in different ways using constructor delegation. Your task is to implement multiple constructors that call each other to avoid code duplication, and a method to display book information.
- Implement constructors using delegation:
- A constructor with
title,author, andyear.
- A constructor with
- A constructor with
titleandauthoronly; setsyearto0. - A constructor with
titleonly; setsauthorto"Unknown"andyearto0.
- Implement a method
printInfothat prints the book information in the format:
"Title: <title>, Author: <author>, Year: <year>"
Example
Book("1984", "George Orwell", 1949) → Title: 1984, Author: George Orwell, Year: 1949
Book("Clean Code", "Robert C. Martin") → Title: Clean Code, Author: Robert C. Martin, Year: 0
Book("Mystery Book") → Title: Mystery Book, Author: Unknown, Year: 0
Book() → Title: Undefined, Author: Unknown, Year: 0
Solution
Thanks for your feedback!
single