← Back to Core Java Course | Chapter 7: OOP Core | Lesson 11 of 11

Java Object Class

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?

java
class Dog {}
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog();
		System.out.println(dog.toString()); // inherited from Object
	}
}

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

java
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());
	}
}

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

java
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));
	}
}

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

java
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());
	}
}

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

java
class Dog {}
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog();
		System.out.println(dog.getClass().getName());
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.