Mohammad
Mohammad

Reputation: 23

Dynamic & Static Binding in Java

I was studying and I came across this piece of code:

class Shoe{
    public Shoe(){
        this("This is 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");
    }
}

I thought the output would be:

A white tennis shoe is created

Because only the constructor of the child class WhiteTennisShoe is invoked. However, the real output is something completely different:

Exam 1
This is a Tennis Shoe
Derived Class
A white tennis shoe is created

Is this because of dynamic and static binding? Or is it pure java inheritance? I am really confused. I have been searching for a good explanation of static and dynamic binding for a few days but I found none.

Upvotes: 2

Views: 478

Answers (2)

jaco0646
jaco0646

Reputation: 17066

It is pure Java inheritance. Every Java constructor implicitly inserts super() as its first line, unless a parent constructor is called explicitly, such as in the second TennisShoe constructor, which explicitly calls super("Exam 1").

See: Subclass Constructors

Upvotes: 0

Colin D
Colin D

Reputation: 5661

Simple java inheritance.

Each constructor for a subclass needs to call the constructor of the class it extends. If you do not make the call yourself, a call to the default constructor of the class extended is added for you.

In the example:

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

is the same as:

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

Upvotes: 2

Related Questions