VortixDev VortixDev - 3 months ago 7x
Java Question

Unique methods for use through the class rather than an object

So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the

keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g.
) rather than solely through the object (
). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that
would work, however
would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.

In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!

Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.



Yes, short answer is no.

But you can put your static members in a dedicated class, so that no instances share any one of them.

MyObject is instance of MyClass, and you aggregate all you static parts in MyStaticThing.

Using static member on an instance can be misleading, so it is a bad practice


While it is possible to access static members from a class instance, it's bad form, and considered by most to be misleading because it implies to the readers of your code thatthere's an instance of the member per class instance.

Another thing, do not use static things, because you cannot do abstraction and replace implementations to extend your code.

Being able to switch between implementations is useful for maintenance and tests.