Skip to content

Compile Time Type VS Runtime Type

Clarence Chew edited this page Oct 10, 2021 · 4 revisions
Compile-time Run-time
Left hand side of the assignment Right hand side of the assignment
The type in which the variable is declared The type the variable is assigned to
Restricts methods that can be called upon declaration/compilation Actual methods to invoke are determined during runtime
Method overloading Method overriding
Static/early binding Dynamic/late binding
Return type of function Actual type of object returned from function

For example:

Circle c = new FilledCircle(1.0, Color.BLUE);

Compile-time type of c is Circle and the runtime type is FilledCircle.
Remember that in Circle.java, we have these methods:

  • Circle(double radius), the constructor
  • double getArea()
  • double getPerimeter()
  • public String toString()

While in FilledCircle.java, we have these:

  • FilledCircle(double radius, Color color), the constructor
  • FilledCircle fillColor(Color color)
  • @Override public String toString(), an overriding method!

Imagine you are in a room of doors with different materials and colors. Different method name means different material.

Therefore, since the compile-time type of c is Circle, we can only call the methods inside Circle.java.

Compile-time type selects which door materials you can have access into.

However, since the runtime type of c is FilledCircle, the actual method called for toString is the overriden method!

For each door material, there may be many doors, and runtime type will decide which color is the correct one.

Also, in PA1, we had to lock a question

public Markable lock() { // returns Markable
    return this; // of type MCQ/TFQ/FillInBlank
}

This would allow:

  • Question::lock().mark() to work
  • Question::mark() to fail
  • Question::answer() to work
  • Question::lock().answer() to fail
Clone this wiki locally