Sitemap

Java Inner Classes-Simplified

5 min readNov 30, 2024

--

Inner Class:

In Java, an inner class is a class defined within another class. It’s like having a smaller box inside a bigger box, where the smaller box (inner class) is used exclusively by the larger one (outer class). This structure keeps the code neat, organized, and encapsulated.

You can think of it like a car having an engine — where the engine is a part of the car.

class Car {
private String model;

public Car(String model) {
this.model = model;
}

// Inner class
class Engine {
void start() {
System.out.println("The engine of " + model + " is starting.");
}
}
}
class Test {
public static void main(String[] args) {
Car car = new Car("Tesla Model S");
Car.Engine engine= car.new Engine();
engine.start();
}
}

//Output: The engine of Tesla Model S is starting.

Output:
The engine of Tesla Model S is starting.

Accessing Inner Classes

Inner classes are accessed through an instance of the outer class.

Types of Inner Classes in Java

  1. Non-Static Inner Class
  2. Static Inner Class
  3. Anonymous Inner Class
  4. Local Inner Class

1. Non Static Inner Class:

Inner classes, are commonly used in real-world scenarios where a nested class depends on and have access to all members (fields and methods) of the enclosing class, including private members.

Characteristics:

  • Requires an instance of the outer class for creation.
  • Has access to all members of the outer class.
  • Implicit reference to the outer class (OuterClass.this).

Example:

Employee Management where inner classes can represent specific roles or responsibilities of an employee within a company.

class Employee {
private String name;
private String designation;

public Employee(String name, String designation) {
this.name = name;
this.designation = designation;
}

class Role {
void displayRole() {
System.out.println("Employee: " + name);
System.out.println("Designation: " + designation);
}
}
}

Instance Creation:

public static void main(String[] args) {
Employee emp = new Employee("John Doe", "Software Developer");
Employee.Role role = emp.new Role();
role.displayRole();
}

Points to remember:

  • Encapsulation: Keeps implementation details hidden.
  • Reusability: The inner class can be reused.
  • Reduced Boilerplate: It has direct access to outer class members.
  • Tight Coupling: Inner classes are tightly coupled to the outer class.
  • Memory Overhead: The inner class holds a reference to the outer class.
  • Increased Complexity: Can add to the complexity of the program.

2. Static Inner Class

A static inner class (also called a nested static class) is declared as static, meaning it does not require an instance of the outer class to be created.

Characteristics:

  • No outer class instance required for creation.
  • Can only access static members of the outer class.
  • Independent of the outer class’s instance.

Example: Utility for a Banking System

Consider a banking application where you need to calculate interest for various account types. A static inner class can be used to encapsulate the interest calculation logic.

class Bank {
private static double baseInterestRate = 5.0;

// Static inner class for calculating interest
static class InterestCalculator {
static double calculateSavingsInterest(double balance) {
return balance * (baseInterestRate / 100);
}
}

Instance Creation:

public static void main(String[] args) {
double savingsInterest = Bank.InterestCalculator.calculateSavingsInterest(10000);
System.out.println("Savings Interest: " + savingsInterest); // Output: 500.0
}
}

Points to remember:

  • Encapsulation: Hides implementation details.
  • Reusability: Can be used independently of the outer class.
  • Independent Nature: Does not require an outer class instance.
  • Tight Coupling: Can still be tightly coupled to the outer class if needed.

3. Anonymous Inner Class

An anonymous inner class does not have a name and is used for instantiating a class with specific behavior, often in situations where defining a full class is unnecessary.

Characteristics:

  • Defined and instantiated in a single expression.
  • Can extend a class or implement an interface.
  • Typically used for short-lived functionality.

Example: Sorting Names Using Comparator

Here sort method of Collections class takes two arguments list and comparator interface implementation i.e anonymous class to sort the name based on their length.

public class SortName {
public static void main(String[] args) {
// List of strings to sort
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Christopher");
names.add("David");

// Sorting using an anonymous inner class for Comparator
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// Compare strings by their lengths
return Integer.compare(s1.length(), s2.length());
}
});
}
}

Instance Creation:

We do not need to explicitly create and pass an instance of a class when using an anonymous class. The point of an anonymous class is that it is created and instantiated in a single expression. The instance is created implicitly as part of the definition of the anonymous class.

Points to Remember:

  • Conciseness: Saves from creating separate class files for one-time-use classes.
  • Event Handling: Commonly used in GUI-based programming (e.g., for button clicks).
  • Custom Implementations: Provides a convenient way to implement custom behavior on the fly.

4. Local Inner Class

A local inner class is defined within a method or a block of code. It is local to the method or block and cannot be accessed outside of it.

Characteristics:

  • Defined inside a method or constructor.
  • Can access local variables of the enclosing method if they are final or effectively final.
  • Used for short-lived purposes such as event handling or one-off custom logic.

Example: Calculator with Local Inner Class

public class Calculator {

public void calculate(String operationType, int a, int b) {
// Local inner class for performing operations
class Operation {
public int execute() {
if (operationType.equals("add")) {
return a + b;
} else if (operationType.equals("subtract")) {
return a - b;
} else {
return 0;
}
}
}
// Create an instance of the local inner class
Operation operation = new Operation();
int result = operation.execute();
System.out.println("The result is: " + result);
}

}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.calculate("add", 5, 3); // Outputs: The result is: 8
calc.calculate("subtract", 10, 4); // Outputs: The result is: 6
}

Instance Creation:

A local inner class can only be instantiated inside the method or block in which it is defined. Trying to create an instance outside of that method will result in a compile-time error.

Points to Remember:

  • Cannot be instantiated outside the method.
  • Can access local variables if they are final.
  • Short-lived objects.
  • Useful for encapsulation of logic within a method.

Conclusion

Java’s inner classes offer flexibility and power when dealing with closely related functionality. By using different types of inner classes — non-static, static, anonymous, and local — you can structure your code more effectively, ensuring better encapsulation, modularity, and reusability.

Get Abhisht pratap singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Each type of inner class serves a specific purpose:

  • Non-static inner classes allow tight coupling and direct access to outer class members.
  • Static inner classes provide independence while still being nested within the outer class.
  • Anonymous inner classes offer concise, temporary solutions for event handling and custom behavior.
  • Local inner classes are ideal for short-lived, method-specific logic.

Understanding when and how to use each type can significantly enhance the maintainability and readability of your Java applications.

“That’s all for this blog! Stay tuned for more insights.
Cheers, and happy learning!”

--

--

Abhisht pratap singh
Abhisht pratap singh

Welcome to my little world -Where logic meets creativity. I am a computer engineer and here I share my thoughts, code and verses.