1
public class CarServices { 
  private CarServices() { } // Prevents instantiation

 //some methods

}

I prevent the constructor from been instantiated is this the correct way, or am I missing something?

nyulan
  • 311
  • 3
  • 12
  • 1
    Yes, that is a common way to prevent instantiation. – khelwood Nov 16 '17 at 12:42
  • @KaustubhKhare It's not a singleton if it is never instantiated. – khelwood Nov 16 '17 at 12:43
  • ignoring the fact that a "non instantiable class" does not make any sense in an OO language in the first place (no not even for "utility classes") you need to make the class `abstract` so that it cannot be instantiated from itself. – Timothy Truckle Nov 16 '17 at 12:44
  • Well, an inner class can still instance it (like a `Builder` implemented in this class) – AxelH Nov 16 '17 at 12:52

1 Answers1

2

You can mark your class - abstract:

public abstract class CarService{
...
}

We can't create instance for abstract class, only extends for this class.

korevikov
  • 47
  • 7