Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time polymorphism

I have a question about compile time polymorphism in java.

Is method overloading a way to achieve compile time polymorphism? If it is, is it the only way? Little example would help me a lot.

I searched in the web and different sources give different answers and its confusing. That is why I thought of asking it here.

Thanks in advance.

like image 851
Supun Amarasinghe Avatar asked Apr 14 '17 17:04

Supun Amarasinghe


People also ask

What is the difference compile time and run time polymorphism?

In Compile time Polymorphism, the call is resolved by the compiler. In Run time Polymorphism, the call is not resolved by the compiler. It is also known as Static binding, Early binding and overloading as well.

What is compile time polymorphism in Java example?

Compile-time polymorphism is a polymorphism that is resolved during the compilation process. Overloading of methods is called through the reference variable of a class. Compile-time polymorphism is achieved by method overloading and operator overloading.

What is runtime polymorphism with example?

Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type.

Why overloading is called compile time polymorphism?

Compile Time Polymorphism in Java is when you have the several methods with same name and different parameters and compiler has to decide how to select which method has to run based on the arguments hence the name Compile time polymorphism or method overloading.


1 Answers

I found this external source. It makes the statement that there is no "compile time polymorphism". You probably mean "runtime polymorphism"?

Essentially, polymorphism refers to the feature that a method is not executed by a fixed method implementation that is defined at compile time, but rather there is a lookup at runtime which method implementation is chosen to execute the call.

For example, there is Object::equals in Java, which has an implementation in the "Object" class. If you create you own class that has its own implementation of the "equals" method, that implementation will be chosen when you compare instances, instead of the implementation defined in the "Object" class.

Polymorphism gets really handy when the complete list of implementations for a method is unknown, e.g. because you provide a library that is used in programs/other libraries that can declare their own (derived) classes that implement the method.

like image 189
Ray Avatar answered Sep 18 '22 20:09

Ray