Re: Doubly Nested Anonymous Classes
"Daniel Dyer" <"You don't need it"> wrote in message
news:op.tssx9xsp8kxvgr@jack.local...
On Wed, 23 May 2007 23:47:11 +0100, Charles Hottel <chottel@earthlink.net>
wrote:
The code below is from Effective Java, item 18. Can anyone explain why
the
book and the comment refer to "doubly nested anonymous classes"? When I
compile the program the names I see have only one dollar sign in them. I
can see they are anonymous claases but why "doubly nested"? Thanks.
// Typical use of a public static member class - Page 94
public class Calculator {
public static abstract class Operation {
private final String name;
Operation(String name) { this.name = name; }
public String toString() { return this.name; }
// Perform arithmetic op represented by this constant
abstract double eval(double x, double y);
// Doubly nested anonymous classes
public static final Operation PLUS = new Operation("+") {
double eval(double x, double y) { return x + y; }
};
public static final Operation MINUS = new Operation("-") {
double eval(double x, double y) { return x - y; }
};
public static final Operation TIMES = new Operation("*") {
double eval(double x, double y) { return x * y; }
};
public static final Operation DIVIDE = new Operation("/") {
double eval(double x, double y) { return x / y; }
};
}
// Return the results of the specified calculation
public double calculate(double x, Operation op, double y) {
return op.eval(x, y);
}
}
The Calculator class is the "top-level" class. The Operation class is a
(static) nested class within the Calculator class. Each of the operations
(PLUS, MINUS, TIMES, DIVIDE) is an anonymous inner class. These anonymous
inner classes are nested within the Operation class, which in turn is
nested within Calculator, hence they are doubly-nested classes (they are
nested within a nested class).
Dan.
--
Daniel Dyer
https://watchmaker.dev.java.net - Evolutionary Algorithm Framework for Java
Ok thanks! I guess imisinterpreted it. My mind was looking for an anonymous
class nested within an anonymous class.