Java Reference
In-Depth Information
A member inner class can be declared
public
,
private
,
protected
or have the default
access.
A member inner class can extend any class and implement any number of interfaces.
A member inner class can be
abstract
or
final
.
An inner class cannot declare static fields or methods.
Most importantly, a member inner class has access to the members of the outer class,
even the private members.
That last property is what makes inner classes so useful and benefi cial. A member inner
class has access to its outer class members without using any special syntax.
Let's look at a simple example to get started. Here is a class named
Outer
that contains a
protected member inner class named
Inner
:
1. public class Outer {
2. private String greeting;
3.
4. protected class Inner {
5. public int repeat = 3;
6. public void go() {
7. for(int i = 1; i <= repeat; i++) {
8. System.out.println(greeting);
9. }
10. }
11. }
12.}
An inner class declaration is like any other top-level class. It can declare fi elds, methods,
constructors, and so on. The
Inner
class has a fi eld named
repeat
and a method named
go
.
However, what makes
Inner
unique is it can access the members of
Outer
.
The important line of code here to focus on is line 8 when the
Inner
class displays the
private
greeting
fi eld of the
Outer
class. For line 8 to make sense, there has to be a unique
greeting
associated with the instance of
Inner
. Otherwise, it is not clear which
greeting
reference to display. What makes this possible are the following properties of inner classes:
An inner class object is associated with exactly one outer class object. This association
is made when the inner object is instantiated with the
new
keyword.
You cannot instantiate an instance of an inner class without a corresponding outer
class instance.
The syntax for instantiating an inner class is to use a reference with the
new
operator.
For example:
Outer a = new Outer();
Outer.Inner b = a.new Inner();
Search WWH ::
Custom Search