Java Reference
In-Depth Information
// A member method for the Tire class
public double getRadius() {
return radius;
}
} // Member inner class declaration ends here
// A constructor for the Car class
public Car(int year) {
this.year = year;
}
// A member method for the Car class
public int getYear() {
return year;
}
}
In Listing 2-2,
Car
is a top-level class and
Tire
is a member inner class of the
Car
class. The fully qualified name for
the
Car
class is
com.jdojo.innerclasses.Car
. The fully qualified name of the
Tire
class is
com.jdojo.innerclasses.
Car.Tire
. The
Tire
inner class has been declared
public
. That is, its name can be used outside the
Car
class. The
constructor for the
Tire
class is also declared
public
. This means you can create an object of the
Tire
class outside the
Car
class. Since
Tire
is a member inner class of the
Car
class, you must have an object of the
Car
class before you can
create an object of the
Tire
class. The
new
operator is used differently to create an object of a member inner class. The
“Creating Objects of Inner Class” section in this chapter explains how to create objects of an inner member class.
Local Inner Class
A local inner class is declared inside a block. Its scope is limited to the block in which it is declared. Since its scope
is always limited to its enclosing block, its declaration cannot use any access modifiers such as
public
,
private
,
or
protected
. Typically, a local inner class is defined inside a method. However, it can also be defined inside static
initializers, non-static initializers, and constructors. Listing 2-3 shows an example of a local inner class.
Listing 2-3.
An Example of a Local Inner Class
// TitleList.java
package com.jdojo.innerclasses;
import java.util.ArrayList;
import java.util.Iterator;
public class TitleList {
private ArrayList<String> titleList = new ArrayList<>();
public void addTitle (String title) {
titleList.add(title);
}
public void removeTitle(String title) {
titleList.remove(title);
}