1

So, in one of the Java tutorials I was watching, I came across this line of code:

Animal mutt = new Dog();

Where Dog extends Animal. This line works, creating a type Animal variable referring to a Dog instance. But I wonder, can't we do this instead?

Dog mutt = new Dog();

Thanks, I hope you can shed light on this.

1 Answers1

1

Yes you can do both. But sometimes there are situations where you need to operate on more than one type. I explain it easier with an example.

public void wash(Animal animal) { /* Happy Washing */ }

If you only can wash a dog but not a cat, then you can use the dog directly. But when you also can wash cats, then you should use Animal instead.

This is called liskov substitution principle [1] and is part of the SOLID Idom [2].

Charlie
  • 1,169
  • 2
  • 16
  • 31