014-008-009

Overriding toString() from Object Class

Easy

Problem Description

Overriding toString() from Object Class

In this problem: You will override the toString() method inherited from the Object class to provide a meaningful string representation for a Book class.

Learning Objective: Understand that all Java classes implicitly inherit from the Object class and learn how to override toString()

Overview

Every class in Java implicitly inherits from the Object class. The default toString() method in Object returns the class name and hash code, but you can override it to provide a meaningful string representation.

Specifications

Book Class

  • Fields: String title, String author, int pages
  • Constructor: Takes all three fields as parameters
  • Override toString(): Returns "Book{title='title', author='author', pages=pages}"

Main Class

  • Create 2 Book instances:
    1. new Book("Java Programming", "John Smith", 450)
    2. new Book("Data Structures", "Jane Doe", 320)
  • Print each instance using System.out.println() (which automatically calls toString())

Output Format

Book{title='Java Programming', author='John Smith', pages=450}
Book{title='Data Structures', author='Jane Doe', pages=320}

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up