Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Anonymous Class. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous Class." Watch "Anonymous Class." New topic
Author

Anonymous Class.

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
The output of this program is :constructor of main class
Anonymous class.

How is the constructor getting invoked??? In this case, the new keyword is used for a different purpose, to create an anonymous class?







[Dave - added code tags]
[ October 12, 2008: Message edited by: David O'Meara ]
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30130
    
150

Abhi,
" Tptest p=new Tptest() {" - This code actually means to create an anonymous subclass of Tptest overriding the methods defined (in your case go.) Just as with a named subclass, the superclass constructor is automatically called.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
The new keyword is used the same way it always is, to create an object (not a class).
What follows the new is whatever is supposed to be used to create the object, usually a constructor call. In this case you have a constructor call included in the anonymous class because you write new TpTest().

[What you write in the class body is whatever is overridden or implemented from the original class of that name-here TpTest.]

Of course you have a constructor; every class which has been compiled has a constructor; in the case of an anonymous class you can't write a constructor, so it uses the same constructor as its superclass. Yes, the original TpTest class is the superclass, and the anonymous class you have written is a subclass of TpTest, and the go() method is overridden.
You have a constructor in the TpTest superclass; when you create an anonymous class object, that constructor is invoked. Remember you always invoke a superclass constructor when you instantiate any subclass. Any "subclass" here means anything other than java.lang.Object.

It is a little like writing super(); at the beginning of a constructor.
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Thanks a lot.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
You're welcome Good to see we are being helpful.
 
jQuery in Action, 2nd edition
 
subject: Anonymous Class.
 
Similar Threads
Is there a way to instantiate anonymous inner class?
StackOverflowError error at Runtime :(
How can anonymous class extend any other class?
Anonymous Inner Class Problem
Anonmyous constructors