jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Could we have classes inside methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Could we have classes inside methods" Watch "Could we have classes inside methods" New topic

Could we have classes inside methods

Chandhrasekar Saravanan
Ranch Hand

Joined: Jun 16, 2002
Posts: 57
Hai ,
could we have classes inside methods, so
whenever we call a method so that the other
class also gets instantiated and can we use the
other class method from the method we call.
Rodney Woodruff
Ranch Hand

Joined: Dec 04, 2001
Posts: 80
You can have classes inside a method but that class would only exist until the program exited the method.

Hope This Helps
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Yes, those would be local classes.
From the JLS: 14.2 Local Class Declarations
[ June 19, 2002: Message edited by: Cindy Glass ]

"JavaRanch, where the deer and the Certified play" - David O'Meara
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

whew.... not quite sure if I understand the question... but it *sorta* sounds like you're looking for a local class, or an anonymous class
These are discussed a lot in the Programmer's Certification Study Forum -- do a quick search in there - I'm sure you'll find some great thread.
Check out this one, it seems promising: A class defined within a method
arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
oops never thought on this..must be interesting..would like to come back after some trials..thanks for such a good thought...
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
You can have classes inside a method but that class would only exist until the program exited the method.
No, the class can continue to exist afterwards - it just can't be referenced as that class from elsewhere in the code. But if a local class implements an interface, you can pass an instance of the local class off to some other object, and the instance can continue to exist, and be referenced as an instance of the interface, long after the method has completed execution.

"I'm not back." - Bill Harding, Twister
Michael Matola
Ranch Hand

Joined: Mar 25, 2001
Posts: 1746
For an example of what Jim's talking about, take a look at Vector's elements method:
Don't get me started about those stupid light bulbs.
subject: Could we have classes inside methods
Similar Threads
Help? Odd Behaviour of Mutator methods
Why private modifier can't use in top class
JVM launcher?
40% for Devakas Final Exam