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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top