+ 7

What is Polymorphism in Object Oriented programming?

polymorphism

6th Nov 2016, 10:33 AM
David Kariuki
David Kariuki - avatar
4 odpowiedzi
+ 4
you think about the Greek roots of the term, it should become obvious. Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on. Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form. So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types). For example, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
6th Nov 2016, 10:33 AM
David Kariuki
David Kariuki - avatar
+ 4
What is the use of answering your own question just after you asked for it? Anyway, polymorphism is the ability to have one method name with various implementations. For instance, if you want to compare an object (say, a person) to another, you could create a function compareTo like that : public void compareTo(Person p) { if(this.age > p.age) System.out.println(this.name + " is older than " +p.name); else System.out.println(p.name + " is older than " + this.name); } Now, if you want to compare it to not only one person but 2, you still can use the same function name and only change the parameters, like that : public void compareTo(Person p1, Person p2) { if(p1.age > this.age && p1.age > p2.age) { System.out.println(p1.name + " is the oldest"); } else if(p2.age > this.age) { System.out.println(p2.name + " is the oldest"); } else System.out.println(this.name + " is the oldest"); } You can also have the same function name with different parameters types, for instance if you want an operation to behave differently if you use an integer or a double. Polymorphism is necessary to create different constructors for the same class, if you want to leave empty ones by example.
6th Nov 2016, 10:45 AM
Pierre Varlez
Pierre Varlez - avatar
+ 1
He just wants to get some achivements, feel good about it, showing off or whatever. The fun part is, he just copy & pastes from stackoverflow. So yeah, at least a downvote is in order.
18th Nov 2016, 10:01 AM
Roland
+ 1
@Pierre Varlez isnt that overloading ?
25th Jan 2017, 4:07 AM
Ashfaque Mohammed Abu
Ashfaque Mohammed Abu - avatar