aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inner classes" Watch "Inner classes" New topic
Author

Inner classes

Jacob Michaels
Ranch Hand

Joined: Mar 23, 2003
Posts: 35
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

Joined: Apr 01, 2003
Posts: 456
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

Joined: Mar 23, 2003
Posts: 35
OK, Thank you, That helps!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inner classes