Java Object Class
In this page:
What is the Object Class?
Every class in Java implicitly extends Object if it doesn't explicitly extend anything else, which is why every object automatically has methods like toString(), equals(), and hashCode() available even if you never wrote them yourself.
Example: What is the Object Class?
class Dog {}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.toString()); // inherited from Object
}
}
Login to try C/C++/Java/PHP code in the editor
The toString() Method
The default toString() inherited from Object prints the class name plus a hash code, which is rarely useful for debugging — overriding it to return meaningful field values is one of the most common customizations you'll make on your own classes.
Example: The toString() Method
class Dog {
String name = "Rex";
@Override
public String toString() {
return "Dog: " + name;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Dog());
}
}
Login to try C/C++/Java/PHP code in the editor
The equals() Method
The default equals() from Object just compares memory references (identical to ==), so two logically-equal objects with different addresses would be considered unequal unless you override equals() to compare actual field values instead.
Example: The equals() Method
class Point {
int x;
Point(int x) { this.x = x; }
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) return false;
return ((Point) obj).x == this.x;
}
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point(5);
Point p2 = new Point(5);
System.out.println(p1.equals(p2));
}
}
Login to try C/C++/Java/PHP code in the editor
The hashCode() Method
hashCode() returns an integer used by hash-based collections like HashMap and HashSet to bucket objects efficiently; Java's contract requires that two objects considered equal by equals() must return the same hash code, or those collections will behave incorrectly.
Example: The hashCode() Method
class Point {
int x;
Point(int x) { this.x = x; }
@Override
public int hashCode() {
return Integer.hashCode(x);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Point(5).hashCode());
}
}
Login to try C/C++/Java/PHP code in the editor
The getClass() Method
getClass() returns the runtime Class object describing an instance's actual type, which is useful for reflection, logging the concrete class name, or distinguishing between subclasses when instanceof checks alone aren't precise enough.
Example: The getClass() Method
class Dog {}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.getClass().getName());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: