This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Could we have classes inside methods

 
Chandhrasekar Saravanan
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
thanks
regards
 
Rodney Woodruff
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have classes inside a method but that class would only exist until the program exited the method.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, those would be local classes.
From the JLS: 14.2 Local Class Declarations
[ June 19, 2002: Message edited by: Cindy Glass ]
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops never thought on this..must be interesting..would like to come back after some trials..thanks for such a good thought...
Arun
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1820
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For an example of what Jim's talking about, take a look at Vector's elements method:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic