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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can a class be instantiated outside main() ?" Watch "Can a class be instantiated outside main() ?" New topic

Can a class be instantiated outside main() ?

nirjari patel
Ranch Hand

Joined: Apr 23, 2009
Posts: 371
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 ?

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11229

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

Joined: Oct 14, 2005
Posts: 18541

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

Joined: Oct 27, 2005
Posts: 19670

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

How To Ask Questions How To Answer Questions
David Newton

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

Joined: Oct 27, 2005
Posts: 19670

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...)
It is sorta covered in the JavaRanch Style Guide.
subject: Can a class be instantiated outside main() ?