Runtime Polymorphismについて

3 min read


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.



Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.




Animal a = new Fish();


  • parent class reference object
  • reference variable of Parent class
  • superclass reference variable


Javaの場合、primitive型以外は全てヒープ領域に保存され、reference variableとして保持される。型は1種類しか持てず、後から変更することもできないが...

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.



Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.

あるサブクラスのオブジェクトがSuperclass referenceとして宣言されメソッド呼び出しが行われた時、親クラスをoverrideしたメソッドの実装が呼び出されるのか、親クラスのメソッドが呼び出されるのかは実行時に決まる。


  • 親クラスの実装を変更することなく、サブクラスのメソッドが詳細な実装を持つことが可能になる
  • テスト済みのクラスを親クラスとして継承することで、再利用可能なコードが増える


Compile time polymorphism

Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading is an example of compile time polymorphism. Method Overloading: This allows us to have more than one method having the same name, if the parameters of methods are different in number, sequence and data types of parameters. We have already discussed Method overloading here: If you didn’t read that guide, refer: Method Overloading in Java.