1

The book im reading says when you override a method in a subclass it means runtime polymorphism. Is there a thing like compile time polymorphism? I thought simple inheritance happens at compile time then polymorphism is runtime.

user1364686
  • 63
  • 2
  • 7

2 Answers2

2

They are hinting at method overloading, which is sometimes referred to as a compile-time polymorphism.

Indeed, method overloading lets you invoke different pieces of code based on the types of objects passed in as parameters. Overloads are resolved at compile time, so the mechanism of overloading could be thought of as a compile-time polymorphism.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • so overloading at compile time, overriding at runtime? – user1364686 Apr 30 '12 at 00:18
  • 1
    @user1364686 As a rule of thumb, yes; the precise explanation takes a couple of pages (see [section 15.12.4.4](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.4.4) of the Java Language Specification for details. – Sergey Kalinichenko Apr 30 '12 at 00:23
1

Lucca Cardelli has a great article named On Understanding Types, Data Abstraction and Polymorphism that explains the answer to your question in great detail.

What you mention in your question is called ad-hoc polymorphism and comprises of method overloading and type cohercions (like those in operator overloading), these two happen at compile time. On the other hand, choosing the right implementation for a given method happens at runtime, this is part of what is called parametric or inclusion polymorphism.

But I am pretty sure Lucca Cardelli will give you a better answer than what I could ever dream of to give.

Recently I participated in another similar question in this forum and I provided some examples of these two types of polymorphism. You might like to give it a look, although I have the impression this is something you may already know.

You may also like to read Polymorphism in Object-oriented Programming languages.

Community
  • 1
  • 1
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • how come calculus is involve in you link? – user1364686 Apr 30 '12 at 00:43
  • This is not calculus as in math, but lambda calculus, one of the most solid bases for understanding computing, and it is briefly mentioned in the article because it helps to introduce some concepts of type theory and this lambda calculus that you mention demonstrates one the most primitive forms of untype systems. The answer to your question is in the first two to five pages, you will not need to delve into all this theory to understand the explanations in the first pages. – Edwin Dalorzo Apr 30 '12 at 01:10