Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility Class - What is the correct approach?

Tags:

java

class

What is the correct approach for a utility class having all methods with public static.
Should I use final class or abstract class?
Please give suggestion.
As for example:

public final class A{ 
    public static void method(){
        /* ... */
    }
}

OR

public abstract class A{
    public static void method(){
        /* ... */
    }
}
like image 709
Shreyos Adikari Avatar asked Sep 21 '12 21:09

Shreyos Adikari


1 Answers

These are some guidelines I've found:

  • All methods must be public static, so that they cannot be overridden.
  • Constructor must be private, so it'll prevent instantiation.
  • Final keyword for the class prevents sub-classing.
  • Class should not have any non-final or non-static class fields.

As you've asked, the class name cannot be abstract (not advisable) -> Which means you are planning to implement it in another class. If you want to prevent sub-classing, use final for the class name; If you want to prevent instantiation, use a private constructor.

like image 65
sarathchandra-0507 Avatar answered Oct 26 '22 21:10

sarathchandra-0507