d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Polymorphism Question
Add Reply New Topic New Poll
Member
Posts: 31,292
Joined: Mar 25 2009
Gold: 0.00
Jan 9 2019 11:39pm
animal wolfdog = new dog();
dog pug = new dog();



^What's the difference between these two? They're both assigning a dog object... I don't see the difference, and what is the polymorphic version used for?
Member
Posts: 12,703
Joined: May 17 2013
Gold: 12,935.00
Jan 10 2019 03:40am
It doesn't really make sense in your example.

The reason polymorphism is useful, is that the parent class can define a number of methods that subclasses override to extend with new functionality.
This means that functions can expect as input a variable with the class Animal, receive a Dog, and still work (since it is a subclass of Animal which just overrides some functionality but has the same signature).

This post was edited by Klexmoo on Jan 10 2019 03:41am
Member
Posts: 1,039
Joined: Jul 8 2008
Gold: 1,939.50
Jan 11 2019 10:12pm
Code

List<Animal> animals = new ArrayList<>();
animals.add(dog);
animals.add(cat);
animals.add(lion);

Given something like the above you could sort all animals by weight, number of legs, whether they have legs, things like that. You couldn't do any of that if you just had a list of dogs.

You can write more generic methods which work more broadly like this:
Code

boolean isBipedal(Animal animal) {
return animal.getNumberOfLegs() == 2;
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll