Constructing objects using inheritance (java)?

Tom :

So the rule states that if B is a subclass of A, then when an object of type A is expected, B will do.

Therefore if I were to have a non-static method in superclass Animals and were to call it using an object of subclass Dog it would function normally e.g. Dog rexy = new Dog(); -> rexy.someMethodFromAnimals();. Then, what benefit do I get from making the static type of that object Animals e.g. Animals rexy = new Dog();. What would this enable?

displayName :

Let's say you have four types of animals - Dog, Cat, Rat and Fish.

Now, you want to be able to keep track of all pets in your home. For that, either you can keep multiple lists of different kinds of animals. Or, you can extract a super-class of type Animal which contains the fields and methods that are common to all animals and keep one ArrayList<Animal> myPets = new ... list for all pets.

The benefit is that when you want to treat all animals as animals you have the ability to do that, even though the animals individually may have entirely different characteristics.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142486&siteId=1