014-005-009
Overriding toString and equals
Medium
Problem Description
Overriding toString and equals
In this problem: You will override the toString() and equals() methods in a Product class to customize object string representation and equality comparison.
Learning Objective: Understand how to override toString() and equals() inherited from the Object class and their practical usage
Overview
All Java classes inherit from the Object class, which provides toString() and equals() methods. The default toString() returns the class name and hash code, and the default equals() compares reference identity (==). In practical classes, these are overridden to provide meaningful behavior.
Specifications
Product Class
- Has
String nameandint pricefields - Constructor
Product(String name, int price)initializes fields - Override
toString()to return"Product{name='<name>', price=<price>}" - Override
equals(Object obj)to returntrueifnameandpriceare equal
Main Class
- Create
Product p1 = new Product("Laptop", 1200) - Create
Product p2 = new Product("Laptop", 1200) - Create
Product p3 = new Product("Phone", 800) - Output
p1.toString()result - Output
p3.toString()result - Output
"p1.equals(p2): "+p1.equals(p2)result - Output
"p1.equals(p3): "+p1.equals(p3)result
Output Format
Product{name='Laptop', price=1200}
Product{name='Phone', price=800}
p1.equals(p2): true
p1.equals(p3): false
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