| Author |
Using class methods without creating an instance of the class
|
Nate Lockwood
Ranch Hand
Joined: Feb 22, 2010
Posts: 75
|
|
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?
Nate
|
 |
Rob McBryde
Greenhorn
Joined: Dec 18, 2010
Posts: 16
|
|
Hi Nate,
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.
|
 |
Nate Lockwood
Ranch Hand
Joined: Feb 22, 2010
Posts: 75
|
|
OK, that makes sense and give me something to think about!
Nothing to do with class Foo being final?
Thanks
|
 |
Rob McBryde
Greenhorn
Joined: Dec 18, 2010
Posts: 16
|
|
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.
|
 |
Nate Lockwood
Ranch Hand
Joined: Feb 22, 2010
Posts: 75
|
|
|
I'll do that, thanks.
|
 |
 |
|
|
subject: Using class methods without creating an instance of the class
|
|
|