• Post Reply Bookmark Topic Watch Topic
  • New Topic

Public constructor in abstract classes  RSS feed

 
Kalyan Anand
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
AFAIK There is no way to create an instance of abstract class. Then why did the Java implementors allow providing a public constructor in an abstract class ?

 
Carl Wauters
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason why you still can write constructors in an abstract class: think about inheritance. A subclass constructor always calls the default constructor of the superclass, even when that superclass in abstract.(unless you explicitly call another one)
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Carl, but that doesn't solve the question. If the constructor of the abstract superclass is protected, the concrete subclass can also access it.

Indeed, it doesn't make much sense to have public constructors in an abstract class. You can't use them directly, since you can't create an instance of an abstract class, and such a constructor doesn't need to be public if a subclass needs to access it.

Also, a subclass does not always access the no-args constructor (what you call 'default constructor'). In the constructor of a subclass you can explicitly invoke a different constructor of the superclass by using the super(...) syntax:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!