aspose file tools*
The moose likes Beginning Java and the fly likes Can a class be instantiated outside main() ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can a class be instantiated outside main() ?" Watch "Can a class be instantiated outside main() ?" New topic
Author

Can a class be instantiated outside main() ?

nirjari patel
Ranch Hand

Joined: Apr 23, 2009
Posts: 374
I am trying following code

I am getting 24 errors.

When I instantiate Hashtable in the main(), it compiles and runs.

So can we not instantiate a class outside main() ? If I dont have a main() in a class, then can I not instantiate any class in that class ?

If I can instantiate a class without main(), then why am I gettingerror in this class CollectionEx ?

Thanks
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11497
    
  16

Generally, you don't create objects outside of METHODS - main or otherwise. So you CAN create objects outside of main, but inside some OTHER method.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

You can also create objects outside any method if you do it as part of the declaration of an instance variable or a class variable. But code which isn't a declaration must be inside some method.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

In the above code, only line 6 is allowed. It declares an instance variable with package-default access and initializes it immediately.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

It's not the instantiation that isn't allowed (line 5 :p) but everything else: a declaration with assignment is different than a statement; statements aren't allowed outside methods (and initializers, as they're sort of different).
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

David Newton wrote:(line 5 :p)

I'm using Opera which (rightfully!) doesn't ignore the line break directly after the [code] tag. Therefore there is one empty line at the start and the code declaration is at line 6.

(Of course Firefox and IE8 do ignore the line break so I'm a minority here...)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can a class be instantiated outside main() ?