I was watching a tutorial on this particular topic and am still unsure of why it would be used. In the tutorial, a sub-class was referred to by it's super-class type (Animal dog = new Dog() ). Why would this be used as opposed of referring to it by putting Dog dog = new Dog()?
Asked
Active
Viewed 64 times
0
-
Because a dog is a Animal. It can do what an animal can do. Instead of making all different animals have all a same method (ex . drink) just put it inside the animal class and all animals have the drink method. – CodingM Jun 11 '18 at 20:20
-
If you're naming the variable `dog` it might as well be type `Dog`. You're right, that isn't a good example. `Animal pet = new Dog()` would be better. More realistically, you'd be setting a field of type `Animal` or calling a method that returns `Animal`, where the point is that any kind of `Animal` is allowed even if the object is a `Dog` in this instance. – Sean Van Gorder Jun 11 '18 at 20:53
-
I don't agree with any of these duplicates, the question says `Animal` is a super-class, not an interface. All those answers are talking about decoupling from implementations, that's not really the question being asked here. – Sean Van Gorder Jun 11 '18 at 21:00
-
Thanks for getting back to me! However i am still a little confused as the why you would use "superclass c = new subclass" or "subclass c = new subclass", if that helps explain my question at all. I understand the implications of using each form however am struggling to understand why you would use each one. – TheRealJW Jun 11 '18 at 21:03
-
Well, like I said, realistically you'd be doing `Animal pet = getAnimal()` and the method might return a `Dog`, or `person.setPet(new Dog())` where it sets the field `Animal pet`. When you have a variable that's declared and set to a `new` object in the same line, you'd usually make the variable type the same as the object (`Dog petDog = new Dog()`), except in cases like `List` where the subclasses are functionally equivalent implementations and it doesn't matter to your code whether it's an `ArrayList` or a `LinkedList`. – Sean Van Gorder Jun 11 '18 at 21:14