• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why abstract class can have constructors

 
debabrata das
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Larry Frissell
Ranch Hand
Posts: 82
2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic