Java
Module 12: Advanced Java Object ConceptsBeginner26 min read

Object Class, Wrapper Classes, Records & Sealed Classes

Override toString, equals, and hashCode properly, use Wrapper classes & autoboxing, and leverage modern Java Records and Sealed classes.

Key Takeaways & Core Concepts
  • `toString()`: Returns a human-readable string representation (default is ClassName@hexHash). Always override it on domain models for clear logs and debugger inspection.
  • `equals(Object o)`: Must be reflexive, symmetric, transitive, consistent, and return false for null.
  • `hashCode()`: Must return the same integer for any two objects where a.equals(b) is true. If you override equals() without overriding hashCode(), two equal objects may land in different HashMap buckets and never be found!
  • Autoboxing: Automatic int -> Integer conversion (Integer.valueOf(x)).

Introduction

Every class in Java—whether built-in or user-defined—implicitly inherits from java.lang.Object. Understanding Object's contract, how Wrapper classes bridge primitives to objects, and how modern Java Records and Sealed Classes eliminate boilerplate is essential for writing idiomatic Java.

Java Record, Wrapper Comparison & Sealed Interface
1import java.util.Objects;
2
3record Student(String name, int roll) {}
4
5sealed interface Shape permits Circle {}
6final class Circle implements Shape {
7 double radius = 3.0;
8}
9
10public class Main {
11 public static void main(String[] args) {
12 Student s1 = new Student("Meera", 101);
13 Student s2 = new Student("Meera", 101);
14 Integer a = 200, b = 200;
15
16 System.out.println(s1);
17 System.out.println("Records equal? " + Objects.equals(s1, s2));
18 System.out.println("Wrapper equals? " + a.equals(b));
19 }
20}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
20 lines
Note: For `Integer` values outside `-128..127`, `a == b` would be `false` because they are distinct objects, whereas `a.equals(b)` is `true`.

Learning Objectives

  • Master the equals() and hashCode() contract and why breaking it corrupts HashMap and HashSet.
  • Understand Wrapper classes, autoboxing/unboxing overhead, and the Integer cache (-128 to 127).
  • Use Nested/Inner classes, Java 16+ Records, and Java 17+ Sealed Classes effectively.

The java.lang.Object Contract

  • `toString()`: Returns a human-readable string representation (default is ClassName@hexHash). Always override it on domain models for clear logs and debugger inspection.
  • `equals(Object o)`: Must be reflexive, symmetric, transitive, consistent, and return false for null.
  • `hashCode()`: Must return the same integer for any two objects where a.equals(b) is true. If you override equals() without overriding hashCode(), two equal objects may land in different HashMap buckets and never be found!

Wrapper Classes, Autoboxing & Integer Caching

Primitives (int, double, boolean) cannot be stored directly in List<T> or Map<K, V>, so Java provides Wrapper classes (Integer, Double, Boolean).

  • Autoboxing: Automatic int -> Integer conversion (Integer.valueOf(x)).
  • Integer Cache Trap: The JVM caches Integer objects from -128 to 127. Thus Integer.valueOf(100) == Integer.valueOf(100) is true, while Integer.valueOf(200) == Integer.valueOf(200) is false! Always compare Wrapper objects using .equals().
  • Performance Tip: Avoid boxing inside tight loops (Long sum = 0L; sum += i; allocates millions of temporary Long objects on the Heap).

Nested Classes, Records & Sealed Classes

  • Static Nested Class: Does not hold an implicit reference to the outer instance (preferred unless outer instance access is needed).
  • Anonymous Inner Class: Inline one-off implementation of an interface/abstract class (largely replaced by Lambdas for functional interfaces).
  • Java 16+ Records: record Student(String name, int roll) {} creates a shallowly immutable data carrier with private final fields, canonical constructor, accessor methods, equals(), hashCode(), and toString().
  • Java 17+ Sealed Classes: sealed interface Shape permits Circle, Rect {} restricts inheritance to an explicit list of permitted subtypes (final, sealed, or non-sealed), enabling exhaustive pattern matching in switch.

Common Mistakes

  • Comparing Integer objects with == instead of .equals().
  • Mutating a field that participates in hashCode() after inserting the object into a HashSet or HashMap—the object becomes "lost" in the wrong bucket!
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)