• Post Reply Bookmark Topic Watch Topic
  • New Topic

-Can an abstract class have a parameterized constructor :  RSS feed

 
Sajan Joseph
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-Can an abstract class have a parameterized constructor :
Can I write :
abstract class A{
int i;
A(int i){
this.i=i;
}
public abstract void doIt();
public void doItAll(){
System.out.println("doItAll");
}
}

A counstructor is used to initialize the state of an object of a class. But an abstract class cannot be instantiated.
Is this question too stupid? I am confused. Please help.
SJ
 
Marilyn de Queiroz
Sheriff
Posts: 9082
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, an abstract class can have a parameterized constructor. This will then be used by the subclasses that extend the abstract class.
 
Sajan Joseph
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Marilyn deQueiroz:
Yes, an abstract class can have a parameterized constructor. This will then be used by the subclasses that extend the abstract class.

Thank you Marilyn
 
Rajendra Deshpande
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marilyn,
How would a subclass use the constructor of the abstract class.As I understand a subclass would have a constructor of its own and would not need the superclass constructor. Please clarify my doubt.
thanks.
 
Sajan Joseph
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Rajendra,
When ever an object of a class is initialized, the inherited state of the object is initialized prior to the state of the object itself.
So if a class has an inheritance hierarchy, then the super class (base class) constructors are called recursively. This will become apparent when the compiler gives an error message if you have not explicitly called the super class constructor and the super class does not have a default constructor. Normally the JRE calls the default constructor of the sureclass automatically to initialize the super class.
You can get further details from Marilyn
SJ
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!