[HD Pg 186, Sec. 8.2.3 - method-selection]
Posted: Fri Feb 08, 2019 2:55 pm
Since primitives are not classes, there is no subclass/superclass kind of relation between
them as such but Java does define the subtype relation for them explicitly, which is as
follows:
double >float >long >int >char
and
int >short >byte
Based on the above, you can easily determine which of the following two methods will
be picked if you call
processData((byte) 10);
void processData(int value){ }
void processData(short value){ }
The short version will be picked because short is a subtype of int and is therefore, more
specific than an int.
Question,
Given these methods,
// void processData(int value){ System.out.println("int");}
void processData(char value){ System.out.println("char");}
void processData(short value){ System.out.println("short");}
From following, call 1 caused and call 2 did not cause, a compiler error (no suitable method found) when I commented out the method with int signature.
1. e.processData(0b101);
2. e.processData((byte)5);
Since byte is a subtype of short, shouldn't have call 1 been fine too? I suspect that is because the compiler is widening to int. If so, why would the compiler widen a byte literal to int?
Thanks
them as such but Java does define the subtype relation for them explicitly, which is as
follows:
double >float >long >int >char
and
int >short >byte
Based on the above, you can easily determine which of the following two methods will
be picked if you call
processData((byte) 10);
void processData(int value){ }
void processData(short value){ }
The short version will be picked because short is a subtype of int and is therefore, more
specific than an int.
Question,
Given these methods,
// void processData(int value){ System.out.println("int");}
void processData(char value){ System.out.println("char");}
void processData(short value){ System.out.println("short");}
From following, call 1 caused and call 2 did not cause, a compiler error (no suitable method found) when I commented out the method with int signature.
1. e.processData(0b101);
2. e.processData((byte)5);
Since byte is a subtype of short, shouldn't have call 1 been fine too? I suspect that is because the compiler is widening to int. If so, why would the compiler widen a byte literal to int?
Thanks