1.4-Software-Development-Principles

Inner and Anonymous classes

Introduction

Anonymous classes have already been introduced in the theory of Lambda Expressions. There is however a detail that we didn’t discuss.

Anonymous classes are always defined within another class, this is called an inner class. That gives them special privileges.

Inner classes can access private fields!

Inner class access example

We show these posibilities with a Runnable inner class:

public class OuterClass {
    private int price = 15;
    
    public Runnable getPricePrinter() {
        return new InnerClass();
    }
    
    public class InnerClass implements Runnable {
        @Override
        public void run() {
            System.out.println(price);
        }
    }
}

By calling the getPricePrinter() method, you are supplied with a rather simple implementation but this is only the beginning.

The example above could have been done with an anonymous class just as easily.

An inner class gives you the ability to create an additional subgroup of methods and possibly data. When that division makes your code more easily understandable that is enough of a reason.

In addition, you are provided with a separately designed implementation that processes your private internal data in a different way.

The big disadvantage remains that you clearly had the need to divide up all of these methods within a single very large class.

Useful interfaces

Java defines a lot of useful interfaces with different purposes. To provide external sources with implementations of these interfaces an inner class or anonymous class can best be the responsibility of your class itself.

Creating a separate instance that is responsible for a slightly different operation on your internal data, allows you to group everything that concerns that responsibility in a dedicated inner (of anonymous) class.

Conclusion

Inner classes helpt you by grouping methods and responsibilities. The standard interfaces that Java provide also help you with choosing functionality that can easily be added using an inner class.