Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

whts the output

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic