1

I have a confusion please help

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
         public void move() {
            System.out.println("Dogs can walk and run");
         }
}

public class TestDog {

 public static void main(String args[]) {
     Animal a = new Animal();   // Animal reference and object
     **Animal b = new Dog();   // Animal reference but Dog object**

     a.move();   // runs the method in Animal class
     b.move();   // runs the method in Dog class
    }
 }

while creating Animal reference but Dog object we could have done

Dog b = new Dog(); 

and we would have the same result, so i just wanted to know whats the difference and when do we use it?

dpak
  • 29
  • 5
  • Similar question. http://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n – OneCricketeer Dec 12 '16 at 03:40
  • 1
    its not clear, my code is not using interface at all. – dpak Dec 12 '16 at 03:44
  • "To program an interface" also applies to regular inheritance (The Animal class). The link I provided gives your answer "it allows you to switch between different implementations of the [Animal class] with ease." For example, A wolf could extend a dog, a wolf is still an animal, and you can easily switch out the implementation. It's more clear which you use if you defined a bark method on the dog class, but not the animal class – OneCricketeer Dec 12 '16 at 03:49
  • @cricket_007 i understand now. thanks – dpak Dec 12 '16 at 04:20

0 Answers0