2

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?

Tom
  • 279
  • 1
  • 11
  • I really don't understand what you mean by "function normally" and "static type of that object Animals". Can you please rephrase? – santamanno Aug 24 '19 at 20:23
  • As in, it would compile and run. Therefore I want to know why one would ever need to create `Animals rexy = new Dog();` instead of just `Dog rexy = new Dog();`. By static I mean the static binding type. – Tom Aug 24 '19 at 20:25
  • Possible duplicate of [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Tom Aug 24 '19 at 20:32
  • Not talking about interface though, in that sense I could search all of SO for similar things and claim "possible duplicate". Plus, I've gotten correct answers so why is it too broad? – Tom Aug 24 '19 at 20:33
  • I doesn't matter if you talk about an interface or just a super class, the answers there explain to use "open"/broad types when possible. That design "rule" applies to your question as well – Tom Aug 24 '19 at 20:37
  • 1
    It is used implicitly in polymorphism, you can pass a list of superclass to a function, and loop over the subclasses and excecute the same overriden method but each subclass object will execut it diferently. – TiyebM Aug 24 '19 at 20:41
  • 2 "Tom"s sure makes this thread confusing – cameron1024 Aug 24 '19 at 22:41

2 Answers2

3

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.

displayName
  • 13,888
  • 8
  • 60
  • 75
1

In short, so you can be as generic as possible. Using Animals dog = new Dog(); admittedly doesn't have much benefit over Dog dog = new Dog();. However, Animals animal = someWebService.getFirstAnimal(); will work, whereas Dog dog = someWebService.getFirstAnimal(); will not compile, since getFirstAnimal() presumably returns an Animal.

BTW, your class should really be called Animal, rather than Animals. It would be odd for you to declare an Integers i = 1;, same goes for custom types

cameron1024
  • 9,083
  • 2
  • 16
  • 36