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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With