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";
    }
}
|       String toString(){

|           return "Shape";

|       }

toString() in Shape cannot override toString() in java.lang.Object

  attempting to assign weaker access privileges; was public
// 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.

public class Fruit {
    private String fruitName;

    public Fruit(String fruitName) {
        this.fruitName = fruitName;
    }
}

public class Fruit2 {
    private String fruitName;

    public Fruit2(String fruitName) {
        this.fruitName = fruitName;
    }

    @Override
    public String toString() {
        return "This is a " + fruitName;
    }
}

public class Main {
    public static void main(String[] args) {
        Fruit kiwi = new Fruit("kiwi");
        Fruit2 blueberry = new Fruit2("blueberry");
        System.out.println(kiwi.toString());
        System.out.println(blueberry.toString());
    }
}

Main.main(null);
REPL.$JShell$13$Fruit@71c1cc8f
This is a blueberry