What is Inner Class in Java: Definition and Examples
inner class in Java is a class defined inside another class. It helps logically group classes and can access members of the outer class directly.How It Works
Think of an inner class as a smaller box placed inside a bigger box. The bigger box is the outer class, and the smaller box is the inner class. The inner class lives inside the outer class and can use the outer class's things easily, like variables and methods.
This setup helps keep related code together, making it easier to organize and understand. The inner class can also be private, so only the outer class can use it, like a secret helper.
Example
This example shows an outer class Car with an inner class Engine. The inner class can access the outer class's model directly.
public class Car { private String model = "Sedan"; class Engine { void display() { System.out.println("Car model is " + model); } } public static void main(String[] args) { Car car = new Car(); Car.Engine engine = car.new Engine(); engine.display(); } }
When to Use
Use inner classes when you want to group classes that belong together logically. For example, if a class needs a helper class that won't be used anywhere else, making it an inner class keeps it hidden and organized.
Inner classes are also useful when the inner class needs to access the outer class's data directly, like in event handling or building complex data structures.
Key Points
- An inner class is defined inside another class.
- It can access the outer class's members directly.
- Helps organize code and hide helper classes.
- Useful for logically grouping related classes.