Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner classes

 
Jacob Michaels
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • 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()
}
}
 
Damien Howard
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
OK, Thank you, That helps!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic