Java Reference
In-Depth Information
To create an instance of InnerAAA , you must have an instance of InnerAA . To create an instance of InnerAA , you
must have an instance of InnerA . To create an instance of InnerA , you must have an instance of OuterA . Therefore,
to create an instance of InnerAAA , you must start by creating an instance of OuterA . The important point is that to
create an instance of a member inner class, you must have an instance of its immediate enclosing class. The following
snippet of code illustrates how to create an instance of InnerAAA :
OuterA outa = new OuterA();
OuterA.InnerA ina = outa.new InnerA();
OuterA.InnerA.InnerAA inaa = ina.new InnerAA();
OuterA.InnerA.InnerAA.InnerAAA inaaa = inaa.new InnerAAA();
Listing 2-12 uses the member inner class called Car.Tire from Listing 2-2 to illustrate the steps needed to create
an instance of a member inner class.
Listing 2-12. Creating Objects of a Member Inner Class
// CarTest.java
package com.jdojo.innerclasses;
public class CarTest {
public static void main(String[] args) {
// Create an instance of Car with year as 2015
Car c = new Car(2015);
// Create a Tire for that car of 9.0 inch radius
Car.Tire t = c.new Tire(9.0);
System.out.println("Car's year:" + c.getYear());
System.out.println("Car's tire radius:" + t.getRadius());
}
}
Car's year:2015
Car's tire radius:9.0
Accessing Enclosing Class Members
An inner class has access to all instance members, instance fields, and instance methods of its enclosing class.
Listing 2-13 declares a class called Outer and a member inner class called Inner .
Listing 2-13. Accessing Instance Members of the Enclosing Class from an Inner Class
// Outer.java
package com.jdojo.innerclasses;
public class Outer {
private int value = 1116;
 
Search WWH ::




Custom Search