In Java 1.1, a class definition can be placed in another class definition. This is called "inner class". Internal classes are useful to us because they can be used to group logically interconnected classes and to control the "visibility" of a class in another class. However, we must recognize that there is a fundamental difference between internal classes and previously described "compositing" methods.
Typically, the need for internal classes is not particularly obvious, at least without immediately feeling that you need to use an inner class. At the end of this chapter, after you've covered all the syntax for the inner class, you'll find a special example. It should be possible to recognize the benefits of internal classes clearly. The
process of creating an inner class is prosaic: placing the class definition inside a class that encapsulates it (see the 3.1.2 section of chapter 3rd "assignment" for this program):
: Parcel1.java
//Creating inner Classes
package c07.parcel1;
public class Parcel1 {
class Contents} {
private int i = one;
public int value () {return i;}
}
Class Destination {
private String label;
Destination (String whereto) {
label = Whereto;
}
String Readlabel () {return label;}
}
Using Inner classes looks just like
//using any other class, within Parcel1: public
void Ship (String dest) {
Contents C = new Contents ();
Destination D = new destination (dest);
}
public static void Main (string[] args) {
Parcel1 p = new Parcel1 ();
P.ship ("Tanzania");
}
///:~
If used internally within the ship (), the use of the inner class appears to be no different from any other class. The only obvious difference here is that its name is nested inside the Parcel1. But you will soon know that this is not the only difference.
More typically, an external class has a special method that returns a handle to an inner class. Just like the following:
: Parcel2.java
//Returning a handle to a inner class
package c07.parcel2;
public class Parcel2 {
class Contents} {
private int i = one;
public int value () {return i;}
}
Class Destination {
private String label;
Destination (String whereto) {
label = Whereto;
}
String Readlabel () {return label;}
}
Public destination to (String s) {return
new destination (s);
}
Public Contents cont () {return
new Contents ();
}
public void ship (String dest) {
Contents c = cont ();
Destination D = to (dest);
}
public static void Main (string[] args) {
Parcel2 p = new Parcel2 ();
P.ship ("Tanzania");
Parcel2 q = new Parcel2 ();
Defining handles to Inner classes:
parcel2.contents c = Q.cont ();
Parcel2.destination d = q.to ("Borneo");
}
///:~
If you want to generate an object of an inner class anywhere other than the outer class non-static method, you must set the type of that object to the external class name. Inner class name, as shown in main ().