Java Reference
In-Depth Information
Self-Test Exercises
(continued)
27. Consider the following class defi nition:
public class
Outs
{
private int
outerInt = 100;
public class
Ins
{
private int
innerInt = 25;
public void
specialMethod()
{
System.out.println(outerInt);
System.out.println(innerInt);
}
}
Other_Members_of_OuterClass
}
Write an invocation of the method
specialMethod
with an object of the class
Ins
. Part of this exercise is to create the object of the class
Ins
. This should be
code that you could use in some class you defi ne.
Nesting Inner Classes
It is legal to nest inner classes within inner classes. The rules are the same as what
we have already discussed except that names can get longer. For example, if
A
has a
public inner class
B
, and
B
has a public inner class
C
, then the following is valid code:
A aObject =
new
A();
A.B bObject =
aObject.
new
B();
A.B.C cObject =
bObject.
new
C();
Inner Classes and Inheritance
Suppose
OuterClass
has an inner class named
InnerClass
. If you derive
DerivedClass
from
OuterClass
, then
DerivedClass
automatically has
InnerClass
as an inner class just as if it were defined within
DerivedClass
.
Just as with any other kind of class in Java, you can make an inner class a
derived class of some other class. You can also make the outer class a derived
class of a different (or the same) base class.
It is not possible to override the definition of an inner class when you define
a derived class of the outer class.
It is also possible to use an inner class as a base class to derive classes, but we will
not go into those details in this topic; there are some subtleties to worry about.