• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What good is a class if its abstract and has a private constructor

 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was just thinking if there is any benefit of having an abstract class and then make it's constructor private. Is there any user of such classes?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First use is for classes that are not instantiable and are really just collections of static utility methods. A well-designed Java program won't have a lot of such classes (they aren't very OO), but occasionally they are useful.

A second use might be a class that has a static factory method returning instances of subclasses of itself. The subclasses would have to be nested inside the main class, or the private constructor would be inaccessible. A need for such classes won't come up often.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:

A second use might be a class that has a static factory method returning instances of subclasses of itself. The subclasses would have to be nested inside the main class, or the private constructor would be inaccessible. A need for such classes won't come up often.


Before Java 5, it was a well-known idiom for implementing typesafe enums.
 
Lucas Lee
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the most famous usage of private constructor is to implmenting a singleton .
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Lucas Lee:
I think the most famous usage of private constructor is to implmenting a singleton .


Yes, but that is generally not in combination with an abstract class, which is the specific topic we're discussing here.
 
Lucas Lee
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:


Yes, but that is generally not in combination with an abstract class, which is the specific topic we're discussing here.


Yes, you're right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic