Invoke a subclass method of an anonymous class

Posted by arjacsoh on Stack Overflow See other posts from Stack Overflow or by arjacsoh
Published on 2012-12-04T22:43:36Z Indexed on 2012/12/04 23:03 UTC
Read the original article Hit count: 333

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about polymorphism