Java Reference
In-Depth Information
Some design patterns are easier to implement using inner classes. For example, the
adaptor pattern, enumeration pattern, and state pattern can be easily implemented using
inner classes.
Implementing a callback mechanism is elegant and convenient using inner classes. Lambda
expressions in Java 8 offer a better and more concise way of implementing callbacks in Java.
I will discuss lambda expressions in Chapter 5.
It helps implement closures in Java.
Programmers can have a flavor of multiple inheritance of classes using inner classes. An inner
class can inherit another class. Thus, the inner class has access to its enclosing class members
as well as members of its superclass. Note that accessing members of two or more classes is
one of the aims of multiple inheritance, which can be achieved using inner classes. However,
just having access to members of two classes is not multiple inheritance in a true sense.
Types of Inner Classes
You can define an inner class anywhere inside a class where you can write a Java statement. There are three types of
inner classes. The type of inner class depends on the location and the way it is declared.
Member inner class
Local inner class
Anonymous inner class
Member Inner Class
A member inner class is declared inside a class the same way a member field or a member method for the class is
declared. It can be declared as public , private , protected , or package-level. The instance of a member inner class
may exist only within the instance of its enclosing class. Let's consider an example of a member inner class shown
in Listing 2-2.
Listing 2-2. Tire Is a Member Inner Class of the Car Class
// Car.java
package com.jdojo.innerclasses;
public class Car {
// A member variable for the Car class
private int year;
// A member inner class named Tire
public class Tire {
// A member variable for the Tire class
private double radius;
// Constructor for the Tire class
public Tire (double radius) {
this.radius = radius;
}
 
Search WWH ::




Custom Search