Java Reference
In-Depth Information
System.out.println("\nRandom integers using local inner class:");
System.out.println(rLocal.getValue());
System.out.println(rLocal.getValue());
System.out.println(rLocal.getValue());
}
}
Random integers using Top-level class:
13145674
-152214550
2023137461
Random integers using local inner class:
984022582
-948114876
1226102834
The RandomInteger class contains a getValue() method. The only purpose of the RandomInteger class is to get a
random integer using its getValue() method. The RandomLocal class is another class, which has a getRandomInteger()
method, which declares a local inner class called RandomIntegerLocal , which inherits the RandomInteger class. The
RandomIntegerLocal class overrides its ancestor's getValue() method. The overridden version of the getValue()
method generates two random integers. It returns the average of the two integers. The LocalInnerTest class illustrates
the use of the two classes. The name RandomIntegerLocal is not available outside the method in which it is declared
because it is a local inner class. Two things are worth noting.
The
getRandomInteger() method of the RandomLocal class declares that it returns an object
of the RandomInteger class, not the RandomIntegerLocal class. Inside the method it is allowed
to return an object of the RandomIntegerLocal class because the RandomIntegerLocal local
inner class inherits from the RandomInteger class.
In the
LocalInnerTest class, you declared the rLocal reference variable of the RandomInteger type.
// Generate random integers using RandomIntegerLocal class
RandomLocal local = new RandomLocal();
RandomInteger rLocal = local.getRandomInteger();
However, at runtime, rLocal will receive a reference of the RandomIntegerLocal class. Since
getValue() method is overridden in the local inner class, the rLocal object will generate
random integers differently.
Anonymous Inner Class
An anonymous inner class is the same as a local inner class with one difference: it does not have a name. Since it does
not have a name, it cannot have a constructor. Recall that a constructor name is the same as the class name.
You may wonder how you can create objects of an anonymous class if it does not have a constructor. An anonymous
class is a one-time class. You define an anonymous class and create its object at the same time. You cannot create
more than one object of an anonymous class. Since anonymous class declaration and its object creation are
interlaced, an anonymous class is always created using the new operator as part of an expression. The general syntax
for creating an anonymous class and its object is as follows:
new <interface-name or class-name> (<argument-list>) {
// Anonymous class body goes here
}
 
Search WWH ::




Custom Search