To answer your questions:
- It's the ability to select more specialized methods in runtime depending on the object being used to call it.
- Of course. Polymorphism could occur with no abstract classes involved.
- No, overloading/overriding are not types of polymorphism.
Here's an example with polymorphism happening with no abstract classes involved.
// non abstract
class A
{
public void a()
{
System.out.println("Hello from A");
}
}
class B
extends A
{
@Override
public void a()
{
System.out.println("Hello from B");
}
}
class C
{
public static void SomeStatic(A a)
{
// HERE IS WHERE POLYMORPHISM OCCUR
a.a();
}
}
Polymorphism in class C
occurs because SomeStatic
method could be call with a Reference to A object or a Reference to B object. If it's called with a reference to A, A
's a
method will be called. If it's called with a reference to B, B
's a
method will be called. This ability of changing, on runtime, the actual method being called is called Polymorphism.
Overloading barely has anything to do with Polymorphism. In fact, you can hace overloading with no inheritance involved if you want. You could even have overloading with no object orientation involved. Overloading is just letting two function to exist with the same name but with different parameters.
Overriding on the other hand, is just re-defining a method on a specialized (inherited) class. Overriding a method is necessary for polymorphism to happen. Otherwise, the would be no DUAL POSSIBILITIES on runtime (take a close look at the example).
Class C is the key to understand it all:
class Main
{
public static void main(String[] args)
{
A a = new A();
B b = new B();
C.SomeStatic(a); // will call A's a
C.SomeStatic(b); // will call B's a
// AND THIS IS POLYMORPHISM
// C will decide WHICH METHOD TO CALL
// only at runtime
}
}
Poly: comes from greek. Means many.
Morph: comes from greek. Means form.
So in Polymorphism there are "many" (poly) "forms" (morph) of calling a method. Which one will be called, depends on the object being used to call the method.