CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Inheritance

Inheritance
More skills
Compare objects

How to compare objects

  • To test if two objects point to the same space in memory, you can use the equals method of the Object class.
  • To test if two objects store the same data, you can override the equals method in the subclass so it tests whether all instance variables in the two objects are equal.

How the equals method of the Object class works

Example 1: Both variables refer to the same object

Product product1 = new Product();
Product product2 = product1;
if (product1.equals(product2)) // expression returns true

Example 2: Both variables refer to different objects that store the same data

Product product1 = new Product();
Product product2 = new Product();
if (product1.equals(product2)) // expression returns false

How to override the equals method of the Object class

Example 1: The equals method of the Product class

public boolean equals(Object object)
{
    if (object instanceof Product)
    {
        Product product2 = (Product) object;
        if
        (
            code.equals(product2.getCode()) &&
            description.equals(
                product2.getDescription()) &&
            price == product2.getPrice()
        )
            return true;
    }
    return false;
}

Example 2: The equals method of the LineItem class

public boolean equals(Object object)
{
    if (object instanceof LineItem)
    {
        LineItem li = (LineItem) object;
        if
        (
            product.equals(li.getProduct()) &&
            quantity == li.getQuantity()
        )
            return true;
    }
    return false;
}
Previous | Object's type | Cast objects | Compare objects | Next