aspose file tools*
The moose likes Beginning Java and the fly likes Static void main Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static void main" Watch "Static void main" New topic
Author

Static void main

Matt Fyffe
Greenhorn

Joined: Jun 19, 2003
Posts: 25
Hey, recently I've been trying to create applications and thus, use public static void main... however, a lot of it is really bothering me. First of all, how can I use ActionListener and the likes with static void main. When I tried, it would say non-static variable this can not be referenced in a static context (button.addActionListener(this));
I looked at a friends code and it seemed he used both public static void main and public void init. I tried to do this myself but init never seems to be called. So my question is, when i use public static void main, how can I get out of being static everywhere?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
You have to create an object inside the main method, usually an instance of the class in which main is a member. For example:


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Matt Fyffe
Greenhorn

Joined: Jun 19, 2003
Posts: 25
ah... thanks a lot... I'll have to try that out
James Clinton
Ranch Hand

Joined: Jun 23, 2003
Posts: 190
Hi Matt
With regards to your friends code, if he is developing an Application the init() methods would never be called.
About Main and Static:
The main method must be declared static as this means that it doesnt belong to the class and can therefore be invoked without the class being constructed first.
To use listeners:
Follow Michael's example above. And in the foo class implement ActionListener and the actionPerformed method as required.

Hope that helps
/ James
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Static void main