This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I found an example that had three classes, a main and two others. One of them, call it Foo, had a couple of methods one of which main called without creating an instance of Foo. I C&Ped the code to find that it works!
I thought that an instance of Foo would need be created by the use of new. BTW I'm not attempting to write applets or webpages.
What's going on? Did I miss a paragraph in my Java book?
The reason this was allowed is because the init() method in the Foo class has been declared as static. This means that it belongs to the class Foo instead of each instance of Foo class you create. Therefore, you are able to call static methods directly via the format Class.method().
A good example of this is the Math class, take a look in the Java API and you'll see that its methods are all static and therefore you can call them within your programs via Math.method(); without the need to instantiate a Math class object.
hope this helps.
Joined: Feb 22, 2010
OK, that makes sense and give me something to think about!
Nothing to do with class Foo being final?
Joined: Dec 18, 2010
A final class simply means that it cannot be extended by a subclass. This behaviour is caused purely by the static keyword.
If you were to remove the static keyword from the init() method in the Foo class, then you would not be able to compile the Launch class as it stands. In this instance you would have to create an instance of the Foo class using the new keyword as you first expected. This is because when the init() method is not static it belongs to each instance of the Foo class which you would have to first create.
Experiment with it to see for yourself, try removing the static. You should then see an error appearing in your Launch class. But by then creating an instance of Foo in your Launch class you will be able to call its init method.
Joined: Feb 22, 2010
I'll do that, thanks.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Using class methods without creating an instance of the class