Using Constructors in Java: Solution, Explanation & Practice
Create a class with a constructor
Problem summary
Create a Book class with a constructor that takes title and author.
Starter code
// Create Book class with constructor(title, author)
// Add getInfo() method
public class Main {
public static void main(String[] args) {
// Create book: "1984" by "George Orwell"
// Print book info
}
}Expected output and test cases
- Book info
1984 by George Orwell
Hints
- Constructor has same name as class
- No return type for constructors
- Use 'this' to refer to instance variables
Validated solution
Reveal Java solution
class Book {
private final String title;
private final String author;
Book(String title, String author) {
if (title.isBlank() || author.isBlank()) throw new IllegalArgumentException("book details required");
this.title = title;
this.author = author;
}
String description() { return title + " by " + author; }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Book("1984", "George Orwell").description());
}
}How to approach the problem
A constructor establishes the values an object needs before it can be used. Private final fields make the Book immutable after construction, while one descriptive method controls its presentation.
Approach
- Choose the fields required for a valid Book.
- Validate arguments at construction.
- Assign through this.field to distinguish fields from parameters.
Time and space complexity
Time: O(1). Space: O(1).
Edge cases to test
- Blank titles and authors are rejected.
- Null has to be rejected separately if it is allowed to reach this constructor.
Common mistakes
- Leaving fields uninitialized and creating a half-valid object.
- Using static fields for data that belongs to each book.
Follow-up challenge
Add an ISBN value object and define equality for two editions.
Related OOP Basics exercises
- Practice Create a Simple Class in Java
- Practice Getters and Setters in Java
- Practice Static Members in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler