Question

Why can't I assign a new value to the String member of the anonymous class in the code below?

When attempting to compile to throws the error: Unresolved compilation problems: Syntax error on token ";" ,, expected. However this is thrown on the line String s = "Value"; which works fine when the line s = "New Value"; is commented out.

public class Example {
    // nested class to help us out
    private class SomeClass {
    }

    // entry point
    public static void main (String args[]){
        Example e = new Example();
        e.performTest();
    }

    // performs the test
    private void performTest(){
        // anonymous class to test
        SomeClass nc = new SomeClass() {
            String s = "Value";
            s = "New Value";
        };
    }
}
Was it helpful?

Solution

The statement s = "New Value"; is not within a method. It's anonymous class, but it's still a class. The problem is equivalent to

public class SomeSubClass {
   String s = "Value";
   s = "New Value";
}

The problem should be more apparent now.

Place the statement in a method or constructor, or initialize s to "New Value" instead of "Value".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top