Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static method main calls non static constr

 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Rob
 
Rashid Ali
Ranch Hand
Posts: 349
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Regards
Rashid Ali
 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic