This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Anonymous Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Anonymous Inner Class" Watch "Anonymous Inner Class" New topic
Author

Anonymous Inner Class

dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330
Hello.
In my anonymous inner class (pls. see code below), i override method1() and then call a newly defined method2() also within the anonymous inner class. Executing method1 from outside the anonymous inner class via a reference variable works just fine. However, executing method2 also from the same reference variable is not visible and results in compile error. How come method1 can see method2 but is not visible from the outside/reference variable?



SCJP 1.4<br />SCWCD 1.4
Steve Lovelace
Ranch Hand

Joined: Sep 03, 2003
Posts: 125
The variable containing your anonymous class is of type SomeObject. Looking at SomeObject, you can see that it only has one method defined: method1(). As far as any class using a 'SomeObject' is concerned, this is the only method it has.
While the anonymous class is a subclass with method2() defined, it has no visibility (outside of the expression in which it is created), i.e., there is no type exposing method2() for any other code to see.
You could do something like this: and "hello" will print, but there is no other point in the code, other than inside the anonymous class, where method2() can be seen.
[ November 19, 2003: Message edited by: Steve Lovelace ]

The Inner that is named is not the true Inner.
dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330
Thanks Steve!
Uma Balu
Ranch Hand

Joined: Aug 22, 2003
Posts: 61
Hi,
In your code, somekindofobject is actually an instance of SomeObject class, and method2 is not defined in the class SomeObject, it is supposed to be a new method of the anonumous class, hence it is not visible to somekindofobject (instance of SomeObject) .
Thanks,
Uma.
dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330
Also got this answer from K&B book:
Polymorphism is in play when anonymous inner classes are involved. Declaring anonymous inner classes is using a super class reference variable type to refer to a subclass object. As such, you can only call methods on an anonymous inner class reference that are defined in the reference variable type.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Anonymous Inner Class
 
Similar Threads
Question (...Inheritance)
About Overridden II (a Mock Question question...)
Why the variable should be declared as final?
Anonymous inner class
class defined inside an interface