Skip to the content.
Introduction to Inheritance 9.1/9.2 9.3/9.4 9.5 9.6 9.7 Hacks

9.7 Object Superclass

DevOps

Object Superclass

Learning Targets:

  • What is the Object class
  • Why is the Object class important to remember

Every class and object created without the extends keyword will be implicitly extended from the Object Superclass. This means it will inherit some basic methods. Some notable methods are:

  1. getClass()
  2. toString()
  3. equals()

So What?

Well its important to keep in mind when writing out your class. If you are planning to have a method in your class/object that matches the basic Object, then it must be a public override because all of the Object methods are public.

  • are some methods from Object such as getClass() that you cannot override.
// this will return an error
class Shape {
    String toString(){
        return "Shape";
    }
}
// this will be fine
class Shape{
    @Override
    public String toString(){
        return "Shape";
    }
}

Popcorn Hacks

Create an example where you execute an unchanged method from Object, then execute a different method from Object that you changed.

class Vegetable {
    private String name;

    public Vegetable(String name) {
        this.name = name;
    }

    // Unchanged method from Object
    @Override
    public String toString() {
        return "Vegetable: " + name;
    }

    // Changed method from Object
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true; // Check for reference equality
        if (obj == null || getClass() != obj.getClass()) return false; // Type check

        Vegetable vegetable = (Vegetable) obj;
        return name.equals(vegetable.name); // Compare names for equality
    }

    public static void main(String[] args) {
        Vegetable carrot = new Vegetable("Carrot");
        Vegetable anotherCarrot = new Vegetable("Carrot");
        Vegetable potato = new Vegetable("Potato");

        // Execute unchanged method
        System.out.println("Unchanged method (toString): " + carrot.toString());

        // Execute changed method
        System.out.println("Changed method (equals): " + carrot.equals(anotherCarrot)); // true
        System.out.println("Changed method (equals): " + carrot.equals(potato)); // false
    }
}

// Create an instance of Vegetable and call main method
Vegetable.main(null);

Unchanged method (toString): Vegetable: Carrot
Changed method (equals): true
Changed method (equals): false