This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Significance of constructors in abstract class

 
Raj Srimandal
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why jvm doesnt give any compile time check and points errors when i have private or public constructor in a abstract class..anyways i cant say new on a abstract class??

public abstract class AbstractClass{
private AbstractClass(){

}
}

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abstract class is designed to be subclassed. when you instantiate the subclass. the subclass constructor access the super class constructor to initialize the instance variable of super class which might be used into your subclass.
for an example:
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Seetharaman Venkatasamy wrote:Abstract class is designed to be subclassed.

Yes, but that does not explain why it is allowed to have a public or private constructor in an abstract class.

I guess that Raj thinks like this: when I create an abstract class with one constructor, which is private, then I can't subclass the abstract class - because a subclass constructor can't call the private constructor. So it is strange that Java allows this - an abstract class that you must subclass, but you can't because it has a private constructor; and you can't instantiate it either because it is abstract?

The answer is that a class can have more than one constructor, and you might for some reason make one or more of your constructors private. The other, non-private constructors could still be called by subclass constructors. The private constructors could be called by other constructors in your abstract class.

For public constructors, I don't know why Java allows them in an abstract class. Since the class is abstract you can't instantiate it, so the only possibility to instantiate it is via a subclass. But public access isn't necessary for that; protected access would be enough.
 
Raj Srimandal
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jes you did echo my thoughts and also an excellent explanation..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic