Why can't I call methods added to an anonymous class in Java?

If an anonymous class extends / implements a class / interface, why can't I add a new method?

In other words, this works:

class A {
    void a() {
        System.out.println("a in A");
    }
}

class B extends A {
    @Override
    void a() {
        System.out.println("a in B");
    }
    void b() {
        System.out.println("b in B");
    }
}

Why this does not work:

class C {
    A anonA() {
        return new A() {
            void b() {
                System.out.println("b in C");
            }
        };
    }
}

Given:

public static void main(String[] args) {
    B b = new B();
    b.b();

    // C c = new C();
    // A anonA = c.anonA();
    // anonA.b();
    // yields:  java: cannot find symbol \ symbol:   method b()
}
+4
source share
1 answer

Method calls at compile time are determined based on the type of expression they invoke. In your example, you are trying to call b()on an expression of type A. Adoes not declare the method b(), and therefore it will not work.

This does not work on your concrete class example Beither

A notAnonA = new B();
notAnonA.b(); // fails to compile

, .

new A() {
    void undeclared() {}
}.undeclared();
+9

All Articles