aspose file tools*
The moose likes Java in General and the fly likes Significance of constructors in abstract class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Significance of constructors in abstract class" Watch "Significance of constructors in abstract class" New topic
Author

Significance of constructors in abstract class

Raj Srimandal
Greenhorn

Joined: Mar 13, 2008
Posts: 10
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

Joined: Jan 28, 2008
Posts: 5575

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

Joined: Aug 16, 2005
Posts: 14146
    
  18


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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Raj Srimandal
Greenhorn

Joined: Mar 13, 2008
Posts: 10
Thanks Jes you did echo my thoughts and also an excellent explanation..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Significance of constructors in abstract class