Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

abstract class constructor  RSS feed

 
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
I have come across a strange looking code, albeit a valid code because the compiler does not complain. Can any one explain the working of this code

The result of running this program is
Hello I am the constructor of an abstract class
Message

Thanks in advance
Sri
 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree that this is strange code.
But it makes sense to call the C'tor of the abstract class. As you know that any class with full implemnentation can be declared as abstract just to force all the users to extend the class.
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is just that we are not used to see a constractor of an abstract class in the code. But abstract class also have a contructor.
I think only the interface cannot have any constructor.
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies....going by the code it is clear that there can be a constructor in an abstract class.
But why do we need a constructor when we cant directly instantiate an abstract class?
or am I missing something ?
Thanks
Sri
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sri , as this code shows the constructor in the abstract class provides a snippet of code that is going to be executed (only) when constructing instances of subclasses.
 
Ambapali Pal
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sri,
I have not read it anywhere why the constructor in abstract class is needed. But my guess is that it is needed to set the value for the instance variable of the abstract class when its subclass is instantiated (unlike the interface where all of them are constant).
Does it help ?
Ambapali
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot All of you guys.
I think I am more clear on this now
Sri
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!