• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Inner classes

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am studying for the SCJP. This code is from Java 2 Sun Certified Programmer & Developer for Java 2, Authors: Kathy Sierra, Bert Bates
My question is: I understand why I can't access the sizzle() through the Popcorn object. I am trying to figure out how I would go about accessing the sizzle() from the anonymous class.
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();
//p.sizzle();
//Not legal! Popcorn does not have a sizzle()
}
}
 
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't think you can access it from anywhere outside of any of the methods in the anonymous subclass. The subclass defenition is created right then and there and the only existence it has is through the reference where it is created, but since this is actually a superclass reference you only get to access the methods declared in the superclass.
However, you can still create new methods in the anonymous subclass, as long as they are only called from within the subclasses overridden methods.
 
Jacob Michaels
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, Thank you, That helps!
 
reply
    Bookmark Topic Watch Topic
  • New Topic