Week 7 — What is meant by polymorphism?
Question of the Week #7
What is meant by polymorphism?
5 Replies
Polymorphism is one of the OOP principles in Java and allow the same action be executing different action depending on the object or class it is used in. If a parent class Animal eat(); method, and Dog, Cat,Mouse We achieve polymorphism by method overriding, where the method has the same keys, but have different code in the body of a method
Submission from svetlemk#3330
Polymorphism is a core concept of object-oriented programming and it basically means that one type of object/call may have different behaviours.
For example, take the following classes:
It is possible to create store either of those objects in a variable of type SomeClass. Depending on the object the variable holds, something different happens when calling
someMethod
:
Java differentiates between compile-time polymorphism and runtime polymorphism.
Compile-time polymorphism means the decision which method is to be called is made at compile-time. If a method is overloaded, the compiler decides which method is called:
assuming there are two methods:
then it is possible to call them and depending on the parameter type, the compiler will decide on a method to be called:
This is only dependent on the type of the variable which is known at compile-time. It doesn't matter what the type of the actual object is at runtime:
On the other hand, runtime polymorphism means the the decision which method to call is made at runtime. In Java, this is the case with overriding (as in the example with
SomeClass
above).
⭐ Submission from dan1st#7327
Polymorphism means the ability for the same static type to have different implementations of the methods it has. To sum this concept up you could say: Same type, different behavior.
When we use this in the following way:
As we can see that even though we have the same contractual method on the same static type the behavior can vary depending on the very specific subclass implementation.
We can lock this behavior down with the
final
modifier on a method.Generally polymorphism means that even though we have the same type we can still achieve different behaviors in the subclass
⭐ Submission from jade#9418