Invoke a subclass method of an anonymous class
- by arjacsoh
I am trying right now to dig into anonymous classes and one question was just arised I 'd prefer not to refer to much details and to pose my question straightforward: How can I invoke the method sizzle() in the following anonymous class:
public 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()
}
}
It is known and definite in polymorphism rules that a refernce of a superclass cannot invoke methods of subclass without downcasting (even if it refers to an object of the given subclass). However in the above case what is the "key" to invoke the sizzle() method?