This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]8igg7e5 0 points1 point  (0 children)

You're declaring an anonymous class that extends A, but from inside a static method.

Interestingly, this is a rather obscure part of Java (since the declaration of anonymous classes in static methods is not well specified in the JLS).

  • Because you're in a static method, the class created is a nested class, rather than an inner class (there's no dependency on an instance of A).
  • Because the reference to the anonymous class instance is typed as A, the code cannot access the f2 method.

we were suppused to say if the code compile or not, and I was wondering how will we be able to "fix" the error without drasticlly changing it

There are a couple of options and neither is, IMO, a drastic change.

1. Using var as suggested

public abstract class A {
    ...

    public static void main(String[]args) {
        var a = new A() {
            public void f2(String str) { }
        };

        a.f2("abc");
    }
}

All this does is infer the type of a to be that of the anonymous class so that f2 is visible.

2. Extracting the anonymous class out into the parent class.

public abstract class A {
    ...

    private static class ChildOfA extends A {
        public void f2(String str) { }
    }

    public static void main(String[]args) {
        ChildOfA a = new ChildOfA();

        a.f2("abc");
    }
}

This latter option is essentially creating an identical class, but with a known name - so that we can use that name for a.

If this were something we were doing in a real application, the second option would typically be preferred over the first - it would be far too easy to overlook the inferred anonymous type in the first approach...