• java.lang.Object is the superclass of all other classes in Java
    • If a class doesn’t use the extends keyword, the class will inherit from this automatically
    • Everyone automatically inherits:
      • String toString()
      • boolean equals(Object other)
      • There are other methods, but those are outside of the course of the exam.

toString: 9.7.1

  • toString() is commonly overridden
    • it is used to print out the attributes of an object
    • you should write one in every class
  • You can call the parent toString using super.toString()
    • Append your attributes on top of this

public class Mario {
  int coins;
  int lives;
  int size = 0;  // 0 = small mario, 1 = med mario, 2 = fire mario

  public Mario() {
    coins = 0;
    lives = 5;
  }

  @Override
  public String toString() {
    return "Coins: " + coins + " Lives: " + lives + " Size: " + size;
  }
}

Equals: 9.7.2

  • equals(Object obj) is used to test if the current object and the object reference passed in are equal
    • The equals method in Object only returns true if the object references refer to the same object

Overriding the equals method: 9.7.3

  • If you want to change how equals works, you can override the method
    • String overrides the inherited method so it returns true when two Strings have the same value
  • To write your own equals method you must:
  1. use the public boolean equals(Object other) method signature
  2. Type cast other to your class
  3. Return whether this object’s attribute(s) equal the other object’s attributes(s) with == for primitive types, and equals for reference types
  4. You can use && if you have multiple things to check
  5. You can use super.equals(other) to check equality in the superclass first (if you have one other than Object) then check your new attributes

Summary: 9.7.5

  • java.lang.Object is the superclass for all other classes in java
  • Object has built in methods and constructors which all other methods inherit
    • see the java quick reference sheet
  • Subclasses of Object often override the equals and toString methods with more specific implementations