Question

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.

  1. Is it done this way to avoid extending Comparable for the whole class?
  2. If so, why? Is it that much easier/readable/something else?
  3. Can this type of anonymous class be written for any interface?
Was it helpful?

Solution

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:

  1. No; it is anonymously extending another class, thus equivalent to defining a class that extends another, so the same rules apply. You must override any abstract methods.
  2. It is more readable because it is all in the same location as the code that requires it.
  3. Yes, any interface or class.

OTHER TIPS

  1. It will definitely affect the scope in terms of whether or not the compare class is accessible outside of your main method.
  2. Increased write-ability. IMHO, at the expense of read-ability. Yeah it looks simple now, but try reading a class with a lot of them. Again, a matter of opinion. How we do things is we typically start off with an anonymous or local class then promote them as the read-ability decreases. However it is great for simple callbacks. The Oracle docs provide a good statement: "Use them if you need to use a local class only once." Oracle Docs
  3. Yes. Any interface or abstract class can be used this way.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top