File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Static method main calls non static constr Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static method main calls non static constr" Watch "Static method main calls non static constr" New topic

Static method main calls non static constr

Paul Salerno
Ranch Hand

Joined: Jan 17, 2002
Posts: 172
public static void main (String args []).
new Test();
I was wondering if someone could enlighten me as to why its valid for the static method main() to invoke a non static method in this case. It was my understanding that static methods could only access static variables or other static methods.
Thanks again in advance.
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
Assuming Test is the name of a class that is accessible to main, you are *not* calling a method, you are creating an object. That's not a method invocation, it's an intance creation expression. The value returned from that call is a reference to the new object you just created. Since there is no left-hand side variable to contain this value, the new object reference is lost. If you had instead written
Test myTestObject = new Test();
then the variable myTestObject would contain a reference to the new Test object you just created.

SCJP 1.4
Rashid Ali
Ranch Hand

Joined: Jan 16, 2001
Posts: 349
In addition to Rob's reply i would like to mention that 'new Test()' is initiallizing constructor of class which is initialized here anonimously without any reference to object of class.
It means one has done all his creation of instance and other local variables in the other methods and used class constructor to initalized and call them.
And now he/she wants to only initiallize the class constructor to initialize/create a class object then this anonimous way of initiallizing class constructor is used like only in main() call 'new Test() ; that's it.
Hope it clarifies more.
Good luck with Java.
Rashid Ali
Paul Salerno
Ranch Hand

Joined: Jan 17, 2002
Posts: 172
Rob and Rashid, thanks for your help. I knew this wasnt method invocation, but I'm glad to find out an expert's explanation. I needed to be sure that I was secure with static vs non-static.
I agree. Here's the link:
subject: Static method main calls non static constr
jQuery in Action, 3rd edition