Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous inner Comparable class in Java method? [duplicate]

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?
like image 279
MayNotBe Avatar asked May 02 '26 02:05

MayNotBe


1 Answers

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.
like image 130
Charles Goodwin Avatar answered May 04 '26 15:05

Charles Goodwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!