Java ProgramsOOPObject Class Methods

Object Class Methods in Java

beginner·  OOP  ·  Object Class

Problem

Every Java class implicitly extends Object, which means every object automatically comes with a default toString(), equals(), hashCode(), and getClass() — even a class that defines nothing of its own.

Create a plain Car class with no overrides, and observe the default behavior it inherits from Object.

Input
new Car("Toyota").getClass().getName()
Output
Class name: Car

Java Program

Java
public class Car { private String make; public Car(String make) { this.make = make; } public static void main(String[] args) { Car car1 = new Car("Toyota"); Car car2 = new Car("Toyota"); System.out.println("Class name: " + car1.getClass().getName()); System.out.println("Default toString starts with class name: " + car1.toString().startsWith("Car@")); // avoids relying on the exact, non-deterministic hash System.out.println("Default equals (different objects, same fields): " + car1.equals(car2)); } }

Output

Class name: Car Default toString starts with class name: true Default equals (different objects, same fields): false

Core Logic

Calling getClass(), toString(), and equals() on a class that overrides none of them reveals exactly what Object itself provides for free — a class name lookup, an identity-based string, and a reference-based comparison.

How It Works
  1. 1car.getClass().getName() returns "Car", the runtime class name — this works on any object at all, since getClass() comes from Object and can't be overridden.
  2. 2car.toString(), left unoverridden, returns a string in the format ClassName@hexHashcode — checking that it startsWith("Car@") confirms the format without depending on the exact, non-deterministic hash value.
  3. 3car1.equals(car2) compares two separately-constructed Car objects with identical make values — since neither overrides equals(), this falls back to Object's reference comparison and reports false, even though their fields match.
  4. 4None of this required writing a single line of code in Car itself — every one of these methods came from Object automatically.
Two Car objects both built with "Toyota" are still reported unequal by the inherited equals(), since it only compares whether the two references point to the same object.
💡

Key Point: This is the deliberate contrast with the dedicated toString(), equals(), and hashCode() override pages — those pages show what happens once you replace this default behavior; this page shows what you get before you do anything at all.

Key Concepts

Object classgetClass()default toString()default equals()

Related Programs