My doubt is how to invoke the method sizzle() in annonymous inner class?
I tried to create an object of type Food,and tried to invoke sizzle() on it,as the annonymous class is in Food.
But getting compile error sayong that it cant find the method sizzle() in Food class.
See, here you are creating subclass for class popcorn and not for food class.Though your annonymous class is in Food.But see the type of p i.e here it is of type popcorn.
popcorn p=new popcorn()
{
....
}
says that p will start referring to subclass of popcorn(subclass of popcorn has no name, therefor anonymous).
now since superclass i.e popcorn donot have sizzle() method, then howcome compiler will allow you to call p.sizzle(); see the reference is of type popcorn.
its somewhat like
class popcorn
{
pop()
{
}
}
class Anonymous extens popcorn
{
pop()
{
}
sizzle()
{
}
class mains
{
public static void main(
String[] args[])
{
popcorn p=new Anonymous();
p.sizzle(); //will it compile??? NEVER since referece is of type popcorn
//and compiler will complain that it dont know about any
//sizzle() method() in class popcorn;
p.pop();//however it will work,and at runtime sublcass's pop() will work
}
}
Hop you are clear...