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. The title and author are read from standard input.
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:
- Use Scanner to read the title from line 1 and author from line 2 of standard input
- Create a Book instance with the read values
- Output Book object with System.out.println (toString() called automatically)
- Explicitly call toString() and output
Input Format
[title]
[author]
Output Format
Title: [title], Author: [author]
Title: [title], Author: [author]
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