Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Nested, Inner and Anonymous Classes

A static nested Order.Item is a shed with its own key; an inner Account.Statement is a room in one house and reads that account's balance; an anonymous Discount takes 20% off 1000 right where it's written. Plus the class files javac makes for each.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Create a static nested class without an outer object
  • Explain why an inner class needs an outer object and can read its fields
  • Write an anonymous class that implements an interface in place
  • Recognise the class files the compiler makes: Outer$Inner and Outer$1

Before you start

  • Java interfaces
  • Java static: fields, methods and blocks

Java lets you write a class inside another class. There are three kinds you'll meet: a static nested class, an inner class, and an anonymous class. They differ in one question: does the inside class need an object of the outside class?

A static nested class: a shed with its own key

package org.studyeasy.s03l16;

// An order that holds one item. Item is a class written INSIDE Order.
public class Order {
    private final String customer;
    private final Item item;

    public Order(String customer, Item item) {
        this.customer = customer;
        this.item = item;
    }

    public void print() {
        System.out.println(customer + " ordered " + item.name);
    }

    // Static nested class: part of Order, but it needs no Order object
    public static class Item {
        final String name;

        public Item(String name) {
            this.name = name;
        }
    }
}
package org.studyeasy.s03l16;

public class Ex01_StaticNested {
    public static void main(String[] args) {
        Order.Item pen = new Order.Item("Pen");   // no Order object needed
        Order first = new Order("Noah", pen);
        first.print();

        // Anonymous object: made inside the call, never given a name
        Order second = new Order("Priya", new Order.Item("Book"));
        second.print();
    }
}
Noah ordered Pen
Priya ordered Book

Think of Order as a house and Item as a garden shed with its own key: you don't need to open the house to use it. new Order.Item("Pen") works with no order in sight; the class name is enough. The Book item is built right inside the call and never stored in a variable. That's an anonymous object (not to be confused with an anonymous class, below). Because Item has no Order of its own, it can't read customer.

An inner class: a room inside one house

package org.studyeasy.s03l16;

// An account that can hand out its own statement
public class Account {
    private final String owner;
    private final double balance;

    public Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    // Inner class (no static): it reads the fields of the account that made it
    public class Statement {
        public String text() {
            return owner + " has " + balance;
        }
    }

    // Each account builds a Statement that belongs to it
    public Statement statement() {
        return new Statement();
    }
}
Account noah = new Account("Noah", 500);
Account priya = new Account("Priya", 100);

// Ask each account for its own statement
Account.Statement n = noah.statement();
Account.Statement p = priya.statement();
System.out.println(n.text());
System.out.println(p.text());
Noah has 500.0
Priya has 100.0
Two Account objects, Noah with 500 and Priya with 100. Each contains its own Statement object, which reads the balance of the account that built it: Noah has 500.0, Priya has 100.0. Account noah owner Noah, balance 500 Statement "Noah has 500.0" Account priya owner Priya, balance 100 Statement "Priya has 100.0"
Each inner object belongs to the outer object that built it, and reads that object's fields.

No static this time, so every Statement belongs to one account. text() uses owner and balance, which aren't declared in Statement; they come from the account that made it. Noah's statement reads Noah's balance, never Priya's.

The trap: new Account.Statement() without an account doesn't compile. The error says an enclosing instance that contains Account.Statement is required. A statement needs an account to read from. Ask an account instead: priya.statement().

An anonymous class: born where it's used

package org.studyeasy.s03l16;

// The contract: every discount says how it changes the bill
public interface Discount {
    double apply(double total);
}
package org.studyeasy.s03l16;

public class Ex03_AnonymousClass {
    public static void main(String[] args) {
        // Needed once, so write the class right here: no name, no extra file
        Discount festival = new Discount() {
            @Override
            public double apply(double total) {
                return total * 0.8;   // 20% off
            }
        };
        System.out.println("To pay: " + festival.apply(1000));
    }
}
To pay: 800.0

Instead of a new class in a new file, you write new Discount() { ... } with the body right there. It's a class with no name that keeps the interface's promise, and Java builds one object from it. Remove apply from the body and it no longer keeps the contract, so it won't compile. For a one-method interface like this, a lambda is usually shorter.

What the compiler makes

Every class, nested or not, gets its own .class file. After javac, the package folder holds:

  • Order$Item.class: outer name, a dollar sign, inner name.
  • Account$Statement.class: inside it the compiler added a hidden field, final Account this$0, a link to the account that built the statement, and a constructor that takes an Account. That's why a statement needs one. Order$Item has no such link.
  • Ex03_AnonymousClass$1.class: the anonymous class, numbered because it has no name. It implements Discount and holds your apply. No this$0 here: it was created in static main, so there's no outer object.

Recap

KindExampleNeeds an outer object?
Static nested classnew Order.Item("Pen")no
Inner classnoah.statement()yes, and reads its fields
Anonymous classnew Discount() { ... }written once, where it's used
Anonymous objectnew Order.Item("Book") inside a callan object never stored in a variable

You won't write these every day, but you'll read them in other people's code.

Keep going in Java · 38 of 79

Previous
Java Interfaces: Contracts and Multiple Inheritance
Next post
Java Enums with Fields, Methods and switch
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • A static nested class: a shed with its own key
  • An inner class: a room inside one house
  • An anonymous class: born where it's used
  • What the compiler makes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.