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.
It allows you to use a class and override a method in a specific case where the usage is isolated and/or relies on access to local variables.
Whether it is easier or not is somewhat subject and down to personal taste. However it means everything is in situé in your code which enables you to understand what is happening without having to browse to another file or another location in your file. In simple cases, like the above, that is generally easier to work with than having to jump around your codebase.
For local to be accessible it would need to be declared final.
To answer your questions specifically:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With