0

As someone who is learning Java I find it hard to pick whether I should create class with empty constructor or making all her methods statics.

If I’m having a class without properties that read files and doing operations on the data and Being called only one’s shout it be static or have empty constructor.

Because I need to call only one method from the class (and he calls the rest) should I make all methods static or should I call her by creating empty object ?

  • If you truly need no properties at all, then the class is a candidate for static methods only. (Make the constructor private in that case.) There are reasons to make classes with no properties. One is for flexibility where you suspect you may have to add properties in the future. – markspace Jan 08 '21 at 23:07
  • 1
    Does this answer your question? [When to use static methods](https://stackoverflow.com/questions/2671496/when-to-use-static-methods) – Petter Friberg Jan 08 '21 at 23:16

1 Answers1

1

Actually it would be a private constructor, not empty as you don't want to instantiate the class. But here are a couple guidelines.

  • Create static methods that don't require accessing instance fields but do some computation. An excellent example of this is the Math.class
  • Instance methods are used when accessing instance fields and possibly changing then. Getters and setters are good examples. Sometimes private helper methods can be declared static.

But don't use static methods as the fundamental type or because they are easier to use (i.e. work in static or non-static context). They are contrary to the concept of OOP.

WJS
  • 36,363
  • 4
  • 24
  • 39