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:
getClass()
toString()
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 Popcorn {
private String flavor;
private int quantity;
// Constructor
public Popcorn(String flavor, int quantity) {
this.flavor = flavor;
this.quantity = quantity;
}
// Unchanged toString() method from Object class
@Override
public String toString() {
return "Flavor: " + this.flavor + ", Quantity: " + this.quantity;
}
// Overriding equals() method from Object class
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Popcorn popcorn = (Popcorn) obj;
return this.quantity == popcorn.quantity && this.flavor.equals(popcorn.flavor);
}
public static void main(String[] args) {
Popcorn popcorn1 = new Popcorn("Butter", 10);
Popcorn popcorn2 = new Popcorn("Butter", 10);
Popcorn popcorn3 = new Popcorn("Cheddar", 5);
// Executing the unchanged toString() method
System.out.println(popcorn1.toString());
// Executing the overridden equals() method
System.out.println(popcorn1.equals(popcorn2)); // true
System.out.println(popcorn1.equals(popcorn3)); // false
}
}