My professor offered this bit of code in an exercise about scope and lifetime:
class AnonymousInnerClassInMethod {
public static void main(String[] args) {
int local = 1;
Comparable compare = new Comparable () {
public int compareTo(Object value) {
return (Integer)value - local;
}
};
System.out.println(compare.compareTo(5));
}
}
Putting aside the fact that local
isn't accessible (that's the exercise) and that Comparable isn't parameterized (oversight?) ... I have never seen this construct and had no idea it was even possible.
- Is it done this way to avoid extending Comparable for the whole class?
- If so, why? Is it that much easier/readable/something else?
- Can this type of anonymous class be written for any interface?