An Inner class is the one which is defined inside another class. This technique doesn’t seem appealing in the beginning but becomes interesting once we start diving deep to explore features like
- Connection of inner class with outer class
- Multiple inheritance
- Anonymous class
Connection with outer class
Inner class can access fields and methods of outer class as if they are its own.
In above example, inner class ‘Engine’ can invoke private fields & methods of outer class ‘Car’ like it would access its own members. This is possible because inner class keeps a reference of outer class object which is used to instantiate the inner class object. Like any other class keyword new is used to create object of inner class but there is a difference here – for inner class we need to specify object of outer class dot new keyword, e.g. c.new in this example.
Inner class is second technique to achieve multiple inheritance in Java, first one being interfaces. There are real life problems where logical solution lies in a single class inheriting from multiple classes or abstract classes; this can be achieved by outer class extending one class and multiple inner classes extending different classes or multiple inner classes extending same base class differently. For example,
Anonymous inner class
It is a technique using which an object can be created of a class definition by skipping class name. It can be useful in cases where we need only one object of a class.
In above example, getFuel() method of RacingCar returns an anonymous class object by implementing Fuel interface. Also, note the semi-colon to end the return statement.