Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulation of static class in java

Tags:

java

What do you think of the following way to simulate a static class in java? You can add non static methods but you wouldn't be able to call them.

 /**
  * Utility class: this class contains only static methods and behaves as a static class.
  */
 // ... prevent instantiation with abstract keyword
 public abstract class Utilities
    {
        // ... prevent inheritance with private constructor
        private Utilities() {}

        // ... all your static methods here
        public static Person convert(String foo) {...}
    }
like image 982
Gerard Avatar asked Jul 17 '26 23:07

Gerard


1 Answers

That is the usual way. However, there is not need for the abstract keyword. Using a private constructor is sufficient because

  • it prevents the creation of objects (from outside the class)
  • it prevents inheritance

The abstract keyword suggests the user that users of the class might implemented the class what is not the case here.

like image 137
dmeister Avatar answered Jul 19 '26 15:07

dmeister