Search code examples
javainheritancesuperclass

inheritance : How child class interact with its parent?


I have the following code :

class Shoe {
    public Shoe(){
        this("thise a shoe");
        System.out.println("Base Class");
     }
    public Shoe(String s){
        System.out.println(s);
    }
}

class TennisShoe extends Shoe {
     public TennisShoe (){
           this("This is a Tennis Shoe");
           System.out.println("Derived Class");
      }
      public TennisShoe(String s){
           super("Exam 1");
           System.out.println(s);
    }
}

class WhiteTennisShoe extends TennisShoe {
     public WhiteTennisShoe(String s){
         System.out.println(s);
}
}

class Test{
   public static void main(String [] args){
       new WhiteTennisShoe("A White Tennis Shoe is Created");
    }

}

the output is :


Exam 1

This is a Tennis Shoe

Derived Class

A White Tennis Shoe is Created


I just can't understand why did not the compiler goes from

the constructor public WhiteTennisShoe(String s) in WhiteTennisShoe class

to the constructor public TennisShoe (String s) in TennisShoe class


Solution

  • In this constructor

    public WhiteTennisShoe(String s){
         System.out.println(s);
    }
    

    You didn't specify which constructor of TennisShoe should be used - there's no super line. When you do that, the compiler automatically picks the superclass constructor with no arguments; and it would be a compile error if there were no such constructor available to it (although it will make its own one if there are no constructors at all defined for the superclass).

    So the TennisShoe constructor that gets called is

    public TennisShoe (){
           this("This is a Tennis Shoe");
           System.out.println("Derived Class");
    }
    

    which of course then calls the other TennisShoe constructor.