This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes whts the output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "whts the output" Watch "whts the output" New topic
Author

whts the output

Venkat Ramsimha
Ranch Hand

Joined: Dec 28, 2004
Posts: 127
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()
}
}

hi all,
whts the output and how is it generated?

thanks
venkat
Ariel Ortiz
Ranch Hand

Joined: May 14, 2004
Posts: 121


The compile time type of variable p is Popcorn, so you may only use methods defined in this class. We know that p actually refers at runtime to a more specialized class, which defines the sizzle method. Usually, you could cast p to this more specific class, but it happens that this more specific class is anonymous, thus the cast is impossible. So, there's no way to call the sizzle method this way. The best option would be to delcare a non-anonymous class:



Hope this helps.

...Ariel
 
wood burning stoves
 
subject: whts the output
 
Similar Threads
Inner classes
Anonymous inner class
K&B Anonymous Inner Class.
Anonyms Inner Class ????
Is there a way to invoke new methods defined in Anonymous classes?