-2

I am new to java. Could anyone explain why the following program not working? Thanks.

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)); 
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Try with `final int local = 1;` (see http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen). – sp00m Jun 20 '14 at 08:34
  • 2
    Please put more effort into formatting your code in future. Look at the preview of your post before you submit it, and ask yourself whether that's how *you'd* want to read it if you were trying to answer. – Jon Skeet Jun 20 '14 at 08:35

2 Answers2

0

You either have to declare local as final:

final int local = 1;

(More information about this matter on this question, as suggested by sp00m).

Or define it as a static field of your class:

class AnonymousInnerClassInMethod {
    private static int local = 1;
    …
}
Community
  • 1
  • 1
arielnmz
  • 8,354
  • 9
  • 38
  • 66
0

First problem: You can't declare a public static void main(String[] args) inside a nested class, unless you mark that class as static as well.

Second problem: The anonymous constructor you use to define the compare's compareTo method cannot access the non-final variable local. This is an error, because the variable might change during/after construction of the object. Hence, if you mark it as final, it is ensured that the variable cannot change.

blueygh2
  • 1,538
  • 10
  • 15