Inner Classes in Java

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

  1. Connection of inner class with outer class
  2. Multiple inheritance
  3. Anonymous class

Connection with outer class

Inner class can access fields and methods of outer class as if they are its own.

inner-class

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.

Multiple inheritance

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,

inner-class-multiple-inheritance

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.

inner-class-anonymous

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s