Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do static objects work?

I know how to work with objects.. but one thing in particular has me scratching my head.
Static methods.

I'll give an example.

Toolkit theKit = Toolkit.getDefaultToolkit(); 

I think that the theKit object now holds new Toolkit(); class.. but im not sure.

Furthermore I can do theKit.getScreenResolution(); now with theKit reference variable.

Is that because Thetoolkit class it self contains that method?

Forgive me, now that I wrote it all out it seems obvious but ill ask anyway. Thank you.

like image 890
Space Ghost Avatar asked Dec 01 '25 06:12

Space Ghost


2 Answers

static methods belong to the class. Not the instance.
Same is with all static member variables.
So you don't need to create an instance of an object to use the method. Since it belongs to the class you just access it via the class name.
A common usage for static methods is utility methods. You don't use an object (and it might not make sense for a concrete object to exist in your design of class hierarchy) and so you access the method via the class

like image 176
Cratylus Avatar answered Dec 05 '25 13:12

Cratylus


This is a design patten. Now given the case, it is necessary that the Toolkit remains singleton. So the library designer made sure that it remains singleton by itself providing a method to getDefaultToolkit.

getDefaultToolkit returns a Toolkit which can be used by the library users.

Now to provide access to such a method, given one cant initialize Toolkit by 'new Toolkit()`, the library provides a static method, which gives access to it

like image 25
Jatin Avatar answered Dec 05 '25 13:12

Jatin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!