Object Superclass
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.
- If a class doesn’t use the
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 inObject
only returns true if the object references refer to the same object
- The
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:
- use the
public boolean equals(Object other)
method signature - Type cast other to your class
- Return whether this object’s attribute(s) equal the other object’s attributes(s) with == for primitive types, and equals for reference types
- You can use
&&
if you have multiple things to check - 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
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.