Using Constructors in Java: 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
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