Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
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
 
Sheriff
Posts: 9087
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
 
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
 
That is a really big piece of pie for such a tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!