Since java is an object orientated language it should exhibit polymorphism. Below is my definitions of a type of polymorphism; ad-hoc polymorphism, and a subtype of that; coercion.
Ad-hoc polymorphism is obtained when a function works, or appears to work, on several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type. There are two types of ad-hoc polymorphism, coercion and overloading.
Coercion is a semantic operation that avoids a type error. The compiler converts one type into another in order to match an argument type in a function call to the parameter type in the function definition. The function definition only works on one type. Compilers implement coercion at compile time.
I have this example working in C++
#include <iostream>
using namespace std;
void display(int a) const
{
cout << "One argument (" << a
<< ')' << endl;
}
int main( )
{
display(10); // returns "One argument (10)"
display(12.6); // narrowing // returns "One argument (12)"
}
Im trying to implement the same program in java without success.
public static void display (int i)
{
System.out.println("One argument (" + i + ")");
}
public static void main (String[] args)
{
display(10); // One argument (10)
display(12.6); // Narrowing (a type of coercion) takes place. One argument (12)
}
but I am receiving the error.
The method display is not applicable for the arguments(double).
Do you know how to convert successfully. Please be aware that I really wish to use coercion technique where the compiler fixes the types automatically. So i casting to int with (int) 12.6 is not an option for me.
If you have another coercion example which exhibits narrowing, I would be grateful if you shared it with me 🙂
Regards.
Java doesn’t allow narrowing coercion but just widening coercion.
So there are allowed:
But not when you are going to lose precision.
EDIT: Actually since a float in java is a standard 4 byte IEEE754 you do actually lose precision but it is allowed in any case, this shows this behavior:
You’ll have:
So the answer is a little bit more fuzzy than it appears.