• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question about constructors and "inheritance"

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I know that constructors are not inherited. But the following mock exam question has me confused. Can someone explain the reason for the answer?
Given the following class definition
class Mammal{
Mammal(){
System.out.println("Mammal");
}
}
class Dog extends Mammal{
Dog(){
System.out.println("Dog");
}
}
public class Collie extends Dog {
public static void main(String argv[]){
Collie c = new Collie();
}
Collie(){
this("Good Dog");
System.out.println("Collie");
}
Collie(String s){
System.out.println(s);
}
}
What will be output?
1) Compile time error
2) Mammal, Dog, Good Dog, Collie
3) Good Dog, Collie, Dog, Mammal
4) Good Dog, Collie
--
The answer is 2. Actually, I guessed it right, but why isn't the answer 4? If constructors are not inherited, why are the parent constructors invoked instead of just the constructor for Collie?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Constructors must be "chained" from subclass to superclass. This ensures that all instance variables are initialized properly. Let's look at this example:

Even though the constructor from the parent class, Animal, is not inherited, it must be invoked. The reason for this is simple: Dog inherits the instance variable name, but it doesn't initialize it - that is taken care of in the constructor of the superclass. Therefore, in order to ensure that all instance variables are initialized properly, the parent constructor must be invoked.
In this case, I invoked it explicitly, but, if you don't invoke a constructor explicitly, an implicit invocation of the parent class' default constructor is inserted.
Take a look at the JLS §8.8.5 Constructor Body for more information.
I hope that helps,
Corey
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic