This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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
 
Similar Threads
K&B Anonymous Inner Class.
whts the output
Is there a way to invoke new methods defined in Anonymous classes?
Anonymous inner class
compilation fails <identifier expected>