• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class instantiating itself in Main  RSS feed

 
George Willis
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had the question of what this was. And after a Google search found this Topic posted(if there is a better way to reference another Post please let me know):
http://www.coderanch.com/t/443871/java/java/Class-create-instance

In summary, the Class XCopy's Main method creates an instance of the XCopy Class.
So, now knowing that this can and does occur my next questions to myself were:
When would I do this?
How can this best be used?
Is this just another option available to a Java developer that has no other special significance?

So far have no answers for myself. What do the higher authorities at JavaRanch have to say?

Thanks
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well one reason to do that would be the reason you have seen. You instantiate an instance of your class in the main method as an entry point to your application.

Another reason you might want to do that would be the Factory Method pattern. Use a search engine for a comprehensive description, but basically your class has a (usually static) method that is responsible for constructing instances of the class. This is useful for example if the construction process is complicated and you don't want the users of your class to have to do it themselves.

Also, this doesn't have to be done in a static method. Non-static methods can also create instances of the class they belong to.

I would say this is nothing special in the sense that there is nothing magic going on here. It is no different to creating instances of the class from a different class. It is certainly useful though.
 
krishna atok
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Main is a static method which belongs to class. It doesn't belongs to object. All static methods and variables are part of class, where as all non-static methods and non static variables are part of object.
Hence in main method which is static we can create an object of it's own class.
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kesava, you can also create instances from non-static methods. This is very useful in for instance immutable value types that have operators defined on them:
This class models moments in time. It has the operator plus defined on it so you can add time to a moment, to get a new moment in time.
 
George Willis
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!