J_Coder
J_Coder

Reputation: 737

How Dynamic binding works in java

I am beginner to java and trying to understand Dynamic binding

when i come across this below example,

class Animal{}  

class Dog extends Animal{  
 public static void main(String args[]){  
  Dog d1=new Dog();  
 }  
}

Here d1 is an instance of Dog class, but it is also an instance of Animal.

here what i dont understand is,How d1 is also become an instance of Animal class when you do inherit in java.

Can someone explain this concept.

Upvotes: 0

Views: 120

Answers (2)

Shehani Perera
Shehani Perera

Reputation: 26

Dynamic binding occurs during the run time.It is also known as Late binding as it occurs in the run time.The type of the object cannot be determined during the compile time.The parent class and the child class has the same method but the method is overridden. Simple example to understand Dynamic binding

class Animal{
    void eat(){
    System.out.println("Animal is Eating");
    }
    }

    class Dog extends Animal{
    void eat(){
    System.out.println("Dog is Eating");
    }
    }

class Test{
public static void main(String [] args){
Animal obj = new Animal();
obj.eat(); // displays Animal is Eating
Animal obj1 = new Dog(); // reference of the parent class
obj1.eat(); // displays Dog is Eating

}
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 270790

Why they say "d1 is also an instance of Animal", what they really mean is that d1 can be used like an instance of Animal. You can use d1 to do everything an instance of Animal can do, including but not limited to:

  • Passing d1 to an Animal parameter

    public static void method(Animal a) { ... }
    ...
    method(d1); // compiles!
    
  • Assigning d1 to a variable of type Animal

    Animal myAnimal = d1;
    
  • Calling methods that is in the Animal class

    d1.move();
    

The reason why you can do all these is all because of that extends keyword.

Upvotes: 1

Related Questions