Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can a class be instantiated outside main() ?

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Clapham
Sheriff
Pie
Posts: 20955
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the above code, only line 6 is allowed. It declares an instance variable with package-default access and initializes it immediately.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic