014-006-005

Object Class: Overriding toString()

Hard

Problem Description

Object class: Overriding toString()

In this problem, you will create a program that defines a Book class with an overridden toString() method returning the title and author in "Title: [title], Author: [author]" format, and displays the result to standard output.

Learning Objective: Understand how to override methods from Object class, the parent of all classes

Overview

All Java classes implicitly inherit from Object class. By overriding the toString() method provided by Object, you can customize the string representation of objects.

Specifications

Create Book class:

  • Private field title
  • Private field author
  • constructor accepts title and author
  • Override toString() method: return in format "Title: [title], Author: [author]"

In Main class:

  • Create Book instance (title: "Java Programming", author: "John Doe")
  • Output Book object with System.out.println (toString() called automatically)
  • Explicitly call toString() and output

Output Format

Title: Java Programming, Author: John Doe
Title: Java Programming, Author: John Doe

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