This is an example I found online while studying about inheritance.
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 b = new Dog();
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
My main confusion is the line in the main method : Animal b = new Dog();
I understand :
- Animal is the class name
- b is object ref
- new for memory allocation
- Dog is constructor call
But where is 'b' referring too exactly?
What is Animal b = new Dog(); doing?
If Dog extends Animal, why is it Animal b = new Dog and not Dog b = new Dog();?
If I had substituted that line with Dog b = new Dog();, what would be the difference from Animal b = new Dog();
bis referencing an instance ofDog, butbis acting as an instance ofAnimal... wolf in sheep's clothing - welcome to polymorphismList<String> list = new ArrayList<>()? To decouple your code from a specific implementation. Same with Animal and Dog. When your dog becomes a Cat, only 1 change is required in your code because using Animal is still correct.Animal b = new Dog();this line means that you can use Animal class's inteface that is you can use Animal's methods in compile time. But in runtime Dog class's methods run.