Inner Classes

Back

Loading concept...

🏠 Inner Classes: The Secret Rooms Inside Your Java House

Imagine you have a big house (that’s your main class). Inside this house, you can build secret rooms that only people inside the house can use. These secret rooms are Inner Classes!


🌟 Inner Classes Overview

What Are Inner Classes?

Think of a regular class like a standalone toy shop on the street. Anyone can walk in!

But an inner class is like a toy-making room INSIDE your house. Only people living in the house know about it and can use it.

Why build rooms inside?

  • 🔒 Privacy - Keep things hidden from outsiders
  • 🤝 Closeness - The inner room can use everything in the house
  • 📦 Organization - Related things stay together
// The House (Outer Class)
class House {
    private String secretCode = "1234";

    // Secret Room (Inner Class)
    class SecretRoom {
        void showSecret() {
            // Can see secretCode!
            System.out.println(secretCode);
        }
    }
}

Real Life Example:

  • 📱 Your phone has a Camera inside it
  • The Camera can use the phone’s battery, storage, screen
  • But it only makes sense INSIDE the phone!

🎭 The Four Types of Inner Classes

Java gives us 4 different types of secret rooms. Each has its own superpower!

graph TD A["Inner Classes"] --> B["Member Inner Class"] A --> C["Static Nested Class"] A --> D["Local Inner Class"] A --> E["Anonymous Inner Class"] B --> B1["Lives inside,<br>needs outer object"] C --> C1["Lives inside,<br>independent"] D --> D1["Lives inside<br>a method"] E --> E1["No name,<br>one-time use"]

🏠 Member Inner Class

The Bedroom That Needs The House

A Member Inner Class is like a bedroom in your house.

  • The bedroom EXISTS only because the house exists
  • The bedroom can use EVERYTHING in the house
  • You need to BUILD the house first, THEN go into the bedroom
class Zoo {
    private String zooName = "Happy Zoo";

    // Member Inner Class
    class Animal {
        String name;

        Animal(String name) {
            this.name = name;
        }

        void introduce() {
            // Can access zooName!
            System.out.println(name +
                " lives at " + zooName);
        }
    }
}

How to Create It?

// Step 1: Build the house (Zoo)
Zoo myZoo = new Zoo();

// Step 2: Create the room (Animal)
Zoo.Animal lion = myZoo.new Animal("Leo");

// Step 3: Use it!
lion.introduce();
// Output: Leo lives at Happy Zoo

🎯 Key Points:

  • ✅ Can access ALL members of outer class (even private!)
  • ✅ Each inner object is tied to ONE outer object
  • ❌ Cannot have static members (except constants)

🏢 Static Nested Class

The Apartment That Doesn’t Need The Building Manager

A Static Nested Class is like an apartment in a building.

  • The apartment is INSIDE the building (organized together)
  • But you DON’T need to meet the building manager to use your apartment
  • It’s independent!
class School {
    private String schoolMotto = "Learn!";
    static String schoolName = "Bright School";

    // Static Nested Class
    static class Student {
        String name;

        Student(String name) {
            this.name = name;
        }

        void introduce() {
            // Can access static members
            System.out.println(name +
                " studies at " + schoolName);

            // CANNOT access schoolMotto!
            // (needs School object)
        }
    }
}

How to Create It?

// No need to create School first!
School.Student kid = new School.Student("Tom");

kid.introduce();
// Output: Tom studies at Bright School

🔄 Member vs Static - The Difference

Feature Member Inner Static Nested
Needs outer object? YES NO
Access private members? YES Only static
Can have static members? NO YES
Creation outer.new Inner() new Outer.Nested()

Simple Rule:

  • Member Inner = Best friend (knows ALL your secrets)
  • Static Nested = Neighbor (shares the address, but independent life)

📍 Local Inner Class

The Temporary Playroom

A Local Inner Class is like setting up a temporary play area inside a specific room (method).

  • It exists ONLY inside that one method
  • When the method ends, the class disappears
  • Perfect for one-time, special tasks!
class MagicShow {

    void performTrick() {
        String magicWord = "Abracadabra";

        // Local Inner Class
        class Rabbit {
            void appear() {
                System.out.println(magicWord +
                    "! Rabbit appears!");
            }
        }

        // Use it right here
        Rabbit bunny = new Rabbit();
        bunny.appear();
    }

    // Rabbit class doesn't exist here!
}

🎯 Key Points:

  • ✅ Can access outer class members
  • ✅ Can access local variables (if they’re final or effectively final)
  • ❌ Cannot use access modifiers (no public, private)
  • ❌ Only visible inside the method

What’s “effectively final”?

void demo() {
    String word = "Hello"; // Never changed
    // word is "effectively final"

    class Greeter {
        void greet() {
            System.out.println(word); // OK!
        }
    }
}

👻 Anonymous Inner Class

The Ghost Helper

An Anonymous Inner Class is like hiring a mystery helper for ONE job.

  • No name (anonymous = “no name”)
  • Created and used in ONE place
  • Perfect for quick, one-time tasks!
interface Greeter {
    void sayHello();
}

class Party {
    void welcome() {
        // Anonymous Inner Class!
        Greeter ghost = new Greeter() {
            @Override
            public void sayHello() {
                System.out.println("Welcome!");
            }
        };

        ghost.sayHello();
    }
}

Why Use Anonymous Classes?

Without anonymous class:

// Need to create a whole class!
class FriendlyGreeter implements Greeter {
    public void sayHello() {
        System.out.println("Welcome!");
    }
}

// Then use it
Greeter g = new FriendlyGreeter();

With anonymous class:

// Create and define in one place!
Greeter g = new Greeter() {
    public void sayHello() {
        System.out.println("Welcome!");
    }
};

Real World Example - Button Click

button.setOnClickListener(
    new OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("Clicked!");
        }
    }
);

🎯 Key Points:

  • ✅ Can implement interfaces
  • ✅ Can extend classes
  • ❌ Cannot have constructors (no name!)
  • ❌ Can only create ONE object
  • ✅ Can access outer class and final local variables

🎨 When to Use What?

graph TD Q["Need inner class?"] --> A{Needs outer<br>object's data?} A -->|YES| B{Used in<br>one method?} A -->|NO| C["Static Nested Class"] B -->|YES| D{Named or<br>One-time?} B -->|NO| E["Member Inner Class"] D -->|Named| F["Local Inner Class"] D -->|One-time| G["Anonymous Inner Class"]

Quick Decision Guide:

Situation Use This
Helper class that needs outer’s private stuff Member Inner
Utility class, just needs to be grouped Static Nested
Temporary class inside one method Local Inner
One-time implementation, no name needed Anonymous Inner

🎉 Summary: The Family of Inner Classes

Think of the Outer Class as a family home:

Inner Class Type Like… Lives Where? Needs Family?
Member Inner Bedroom Anywhere in house YES
Static Nested Garage apartment In house, own entrance NO
Local Inner Temporary fort Inside one room only YES
Anonymous Ghost helper Appears once, then gone YES

Remember:

  • 🏠 Member Inner = Loyal family member
  • 🏢 Static Nested = Independent roommate
  • 📍 Local Inner = Temporary visitor
  • 👻 Anonymous = Mystery one-time helper

Now you understand the secret rooms inside Java classes! Each type has its special power - choose wisely based on what you need! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.