Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance Doubt #1

 
omkar patkar
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I was just trying a program in eclipse. The dbt is, why does the parameterized constructor in the sub class need to make an implcit call to the non-parameterized constructor in the super class ?

e.g :-

 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what behavior you expected:

Since the SubClassB constructor (with the String argument) will not automatically call the SuperClassA constructor (with the String argument), the compiler will "insert" a "super()" in the SubClassB constructor. But the noargs-constructor does not exist in SuperClassA. So the compilation will fail.
Solution: Either implement a no-args-constructor in SuperClassA or perform an explicit call to the one-args-constructor of SuperClassA (i.e. "super(identity)" )in the first line of the SubClassB-constructor.
 
omkar patkar
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Anton ! I was thinking if i had written a no-argument constructor in the sub-class then the compiler would insert a no-argument call to super class constructor, then SIMILARLY the PARAMTERIZED constructor in subclass would also insert a call to PARAMETERIZED constructor in super class ! .... but i think as per what you said my understanding was WRONG ! Thanks !

But, what possible harm it would make if compiler inserts an implicit call to PARAMETERIZED constructor in the superclass from PARAMETERIZED construtor of subclass ...i.e.,



OR why does the compiler inserts a call to no-argument constructor in the superclass ? ...why it can't be just :-

 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1st way: (does not compile!!)

A is a subclass of Object. If it would be done the way you suggested, the compiler would add the "super(str)". But the class Object doesn't have the constructor Object(String a). So, compilation would fail.

2nd way:

If there would not be an implicit call to the noargs-constructor of A,
(remember, B is-a A)where does B's x (inherited) come from? Who will construct the A-part of B?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic