Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cons of static utility classes in java?

Tags:

java

static

What are the cons of creating static utility classes? The more I've made, the more I find them extremely useful. I understand that they lack object oriented design, but I still love them probably more than I should. Are there any other cons for their use?

like image 326
ahodder Avatar asked Jul 10 '11 15:07

ahodder


People also ask

What is the disadvantage of static in Java?

in static method we cannot call normal functions that is non - static functions. The static method can not use non static data member or call non-static method directly. this and super cannot be used in static context. Access only static type data (static type instance variable).

Should utility classes be static Java?

If the same can be said for your utility class, definitely make it static. This hold true for all methods that do not rely on the state of the object. Not just utility class methods.

What is wrong with static class?

Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.

Should you avoid static in Java?

They avoid trouble. Use static methods as often as possible. That's because static methods can't access the object's attributes. Static methods aren't part of the object, so they don't have access to anything that belongs to the object.


1 Answers

There is nothing wrong with them, in the right context. If you have free-standing, stateless methods (such as those found in java.lang.Math), then a static class is the perfect place for them. The only reason they're in a class at all is because Java has no concept of free-standing methods.

like image 136
Oliver Charlesworth Avatar answered Sep 19 '22 00:09

Oliver Charlesworth