The anonymous class's method must override/implement a method of its superclass to be accessible from the outside. There is no way around writing more boilerplate to achieve your goal, unfortunately.
How to invoke anonymous inner classes's methods?
-
27-11-2021 - |
Domanda
I understand this code is not legal:
class Popcorn {
public void pop() {
System.out.println("popcorn");
}
}
class Food {
Popcorn p = new Popcorn() {
public void sizzle() {
System.out.println("anonymous sizzling popcorn");
}
public void pop() {
System.out.println("anonymous popcorn");
}
};
public void popIt() {
p.pop(); // OK, Popcorn has a pop() method
p.sizzle(); // Not Legal! Popcorn does not have sizzle()
}
}
What then is a way to invoke the sizzle method at all?
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow