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()
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With