| Author |
why abstract class can have constructors
|
debabrata das
Greenhorn
Joined: Nov 12, 2008
Posts: 1
|
|
why we can have/write constructor of an abstract class, if we can't instantiate. why it is so? It is unnecessary. check this out......... public abstract class javaRanch{ public javaRanch(){ } javaRanch(int i){ } }
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
Not really an advanced question. Please try to CarefullyChooseOneForum before posting. Abstract classes, unlike Interfaces, can be used to suggest the structure of the code that extends it. So suppose I write an abstract class that has one imutable property and I expect all classes that inherit from this to supply this property I could define a constructor that takes this property and define a no-args constructor as private.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
Larry Frissell
Ranch Hand
Joined: May 16, 2008
Posts: 82
|
|
debabrata das asked
why we can have/write constructor of an abstract class, if we can't instantiate.
Abstract class's constructor can be called if it is followed by the body for the anonymous class, see notes in JavaNotes
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Originally posted by debabrata das: why we can have/write constructor of an abstract class, if we can't instantiate. why it is so? It is unnecessary.
It is not unnecessary. You can regard an abstract class as an incomplete class: some parts of it are implemented, but other parts are left for a concrete subclass to implement. When you create an instance of the subclass, then the constructor of the abstract superclass is also called. Example: In this example, the constructor of class Animal initializes the field 'name' in the Animal class. So, you see that the constructor is not unnecessary.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: why abstract class can have constructors
|
|
|