0

Could you explain polymorphism in Java in a simple way?

I’m learning about abstract classes and polymorphism and it’s brand new concepts (pretty hard ones at that ahah) and just wanted to know if anyone here had a good/basic/fun way to explain it?

23rd Sep 2017, 10:10 AM
matilda
matilda - avatar
1 Answer
+ 1
Polymorphism basically means that one thing can be or do different things. It comes in lots of different forms. In Java you'll usually encounter # Subtyping: class Animal { } class Dog extends Animal { } now you can use a "Dog" for any function that needs an "Animal", like this public void iWantAnAnimal(Animal a) { } iWantAnAnimal(new Dog()); # Ad-Hoc Polymorphism (overloading): That's when a function does multiple things depending on type. public Integer doubleMe(Integer i) { return i + i; } public String doubleMe(String i) { return i.concat(i); } There's lots of other types of polymorphism, those are the main ones found in Java though. Hope that helps!
23rd Sep 2017, 10:24 AM
Schindlabua
Schindlabua - avatar