Inner Classes, Anonymous & Enum π’¶
Mentor's Note: Not every class needs to be a "Global Citizen." Some classes only exist to help another class (Inner), some are used just once and thrown away (Anonymous), and some are just a list of fixed choices (Enum). π‘
π The Scenario: The Smartphone System π±¶
Think about a high-end smartphone.
- The Inner Class (The Battery): The Battery lives inside the phone. It isn't sold as a standalone device; it's part of the phone and uses its internal power system. π
- The Anonymous Class (The One-Time Update): An OTA Update runs once to fix a bug and is then deleted. You don't create a permanent class for it; you just "run and done." ποΈ
- The Enum (The Model Color): You can only buy the phone in BLACK, WHITE, or GOLD. These are fixed choices that never change. π¨
π¨ Visual Logic: The Smartphone Interior¶
graph TD
subgraph Outer: ["Smartphone π±"]
A[Battery π (Inner Class)]
B[Camera π· (Inner Class)]
end
C[OS: ANDROID βοΈ (Enum)]
D[One-time Fix ποΈ (Anonymous Class)]
π Concept Explanation¶
1. Inner Classes (Nested)¶
An Inner Class is a class defined inside another class. It has a "Special Power": It can access private members of the Outer class! - Use: Group classes that belong together logically.
2. Anonymous Classes π€¶
An Anonymous class is a class without a name. You declare it and instantiate it at the same time. - Use: When you only need to override a method for one-time use (like an event listener).
3. Java Enums (Fixed Choices) π·οΈ¶
An enum is a special "class" that represents a group of Constants (unchangeable variables).
- Use: When you have a predefined set of values like Days, Months, or Colors.
π» Implementation: The Advanced Lab¶
π Sample Dry Run (Enum Switch)¶
| Step | Action | Logic | Result |
|---|---|---|---|
| 1 | ModelColor.GOLD |
Lookup the constant list | Constant found β |
| 2 | switch(myColor) |
Compare with case "GOLD" | Match found! π― |
π Technical Analysis¶
- Inner Class Lifetime: An inner class object can only exist if an outer class object exists. You first create the Phone, then you get the Battery! ποΈ
- Anonymous Class limitation: You cannot write a constructor for an anonymous class because it doesn't have a name to use!
π― Practice Lab π§ͺ¶
Task: The Traffic Light
Task: Create an enum called TrafficLight with RED, YELLOW, and GREEN. Use a switch statement to print "Stop," "Wait," or "Go" based on the light.
Goal: Master using Enums for decision-making. π‘
π‘ Interview Tip π¶
"Interviewers love asking: 'What is the difference between a
staticinner class and a regular inner class?' Answer: A regular inner class needs an object of the outer class to exist. A static inner class does not! Itβs like a separate class that just happens to be inside another one."
π‘ Pro Tip: "Enums make your code type-safe. Instead of checking if a string is 'RED', you check the Enum. No more typos!" - Vishnu Damwala