3

I have class which must work as util . I do not need its instance , all what it contains are static members and static functions . So What's best way to do that ? Make it final with private constructor as Math class in java or just make its constructor private without making it final ?

  • Eh, whatever, it doesn't much matter. If the constructor's private it can't be subclassed anyway. – Louis Wasserman Jul 14 '16 at 03:11
  • if its not final, but has a private ctor, it can still be sub-classed by an inner static class. Having it be both final and a private ctor makes it easier for a reader to tell its purpose, so I would do that. – flakes Jul 14 '16 at 03:14
  • somewhat a duplicate of: http://stackoverflow.com/questions/309553/should-helper-utility-classes-be-abstract and http://stackoverflow.com/questions/12538487/utility-class-what-is-the-correct-approach and http://stackoverflow.com/questions/25223553/how-can-i-create-an-utility-class – alexbt Jul 14 '16 at 03:14

2 Answers2

1

private constructor is enough, no need to mark the class final, by having the private constructor we can't subclass it

If you make the constructor private you can still access it using reflection.

Better approach is throw AssertionError

public class Util {    
    private Util() {
        throw new AssertionError("Can't instantiate");
    }
    // static methods
}

Below code is to instantiate private constructor

public class Test {
    public static void main(String[] args) {
        try {
            Constructor<Util> utilC = Util.class.getDeclaredConstructor();
            utilC.setAccessible(true);
            Util u = utilC.newInstance(); // instance           
        } catch (Exception e) {
            // exception handling
        }
    }
}
Saravana
  • 11,085
  • 2
  • 29
  • 43
0

for the util class,you no need provide constructor.because this functions are static,you can use like this: Util.a()

  • 1
    I'm pretty sure he knows the benefits of static methods. He's wondering if he should make the class abstract or final or non-final with private constructor. He's basically asking which one is considered the best practice. – alexbt Jul 14 '16 at 03:54
  • thanks.in my opinion,if the class only provide static methods ,use private constructor is better – Melody4java Jul 14 '16 at 06:36