I am currently studying the topic 'Methods and Encapsulation' from Jeanne Boyarsky and Scott Selikoff.
Now, I tried the following snippets of code :
Case 1 :
Now, when I compile these classes, in Case 1, it works fine and I get the output as :
From method m1...returning short to int
In case 2, however, I get a compile -time error :
error: incompatible types : possible lossy conversion from int to short
short num = m1();
Am failing to understand, if it is promoting the returned short value in case 1, why is it not working in Case 2.
Can anybody please provide a logical explanation for the same?
Help will be appreciated as always
Thank you in anticipation.
In both cases youo are returning an int from line 12. At least it would be line 12 if you used the correct number of empty lines:-Your method might have a short as its local variable, but to other code its return type is int. That is how it is declared. The compiler doesn't go through the code to test whether there is a “narrower” type returned. In the first code block, you are doing nothing with the value returned, which simply disappears into cyber‑limbo never to be seen again. The second code block attempts to assign an int to a short reference, which as you know can only be done with an explicit narrowing conversion (=cast). Please remind yourself of the kinds of conversions allowed and not allowed, from the Java® Language Specification (=JLS). If you don't supply a cast, your code won't compile.