Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If an anonymous class is extending/implementing 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 doesn't this 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()
}
like image 802
jordanpg Avatar asked Jan 10 '23 16:01

jordanpg


1 Answers

Method invocations, at compile time, are determined based on the type of the expression they are invoked on. In your example, you are attempting to invoke b() on an expression of type A. A does not declare a b() method and so it won't work.

It does not work on your concrete B class example either

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

You can very well add a new method inside the body of the new anonymous class, but you'll only be able to use it within the class or on the actual new anonymous class instance creation expression.

new A() {
    void undeclared() {}
}.undeclared();
like image 127
Sotirios Delimanolis Avatar answered Jan 28 '23 03:01

Sotirios Delimanolis