TickleMonster TickleMonster - 3 months ago 5x
Java Question

Different ways polymorphism is used in java

I am beginner trying to figure out polymorphism and where exactly it occurs in java. Just want to make sure my understanding is correct.

So Polymorphism means to take different shape or to have a different form. My question is are these example of polymorphism?

  1. Polymorphism would result from inheritance between supper classes and its child classes/sub classes objects. The child classes/sub classes would have some additional attributes/instance variables that the parent classes would not. Also, the child classes would also be different from other child classes in that they too would have different attributes that the other children classes may not share. This would result in related but different objects and this is an example of polymorphism.

  2. Method overloading (ad-hoc polymorphism)- Here polymorphism occurs because we have different methods, so different forms, but ultimately proivdes the same action i.e changeColor(). The correct method is chosen based on the argument passed.

  3. Method overriding (pure polymorphism)- Occurs when a single method implementation can be used with a variety of related objects i.e ojects and child classes.

Am I striking out or does this sound okay?


Java has 4 kinds of polymorphism:

  1. Subtyping - overriding inherited methods, or implementing methods from interfaces
  2. Parametric - generic types and methods
  3. Overloading based on method signature
  4. Coercion - implicit casts such as widening of integers, boxing of primitive types and converting objects to strings, e.g. in "" + someObject

(BTW, "ad-hoc" vs. "pure"/"universal" polymorphism is an anachronistic and unhelpful dichotomy, in my opinion.)