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

  1. Constructor has same name as class
  2. No return type for constructors
  3. Use 'this' to refer to instance variables

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler