Search code examples
javaabstract-classprivateencapsulation

Side effects of making a class abstract with the primary goal to prevent it from being instantiated?


I know the approach is to make the constructor private, But why should we do it by making the method abstract,What are it side effects is my question?


Solution

  • Disclaimer: the question was altered heavily and thus I don't think my answer really answers it anymore. Sadly I can't answer the new question as in further discussion in the comments it became clear that there seems to be some confusion.


    Turning the default constructor private will make it so other classes can not create objects of this class. Because how are they going to access the constructor function? They can't. But that doesn't mean you can not create objects of this class. The same way you can access private variables via a getter or setter function you could still create instances of this class. You just have to do it inside the class itself and distribute them to the outside.

    An example of this is the Singleton design pattern. There you generate a single instance which you can access via a getter function.


    An abstract class on the other hand can not be used to create objects at all. They are templates that are supposed to hold common data structures and functions. You can force the implementation of functions via abstract functions.