问题
I have found a similar question, but it didn't really concern the interface issue - Issue about casting object brackets
public class Speak { /* Line 1 */
public static void main(String[] args) { /* Line 2 */
Speak speakIT = new Tell(); /* Line 3 */
Tell tellIt = new Tell(); /* Line 4 */
speakIT.tellItLikeItIs(); /* Line 5 */
(Truth)speakIt.tellItLikeItIs(); /*Line 6 */
((Truth)speakIt).tellItLikeItIs(); /* Line 7 */
tellIt.tellItLikeItIs(); /* Line 8 */
(Truth)tellIt.tellItLikeItIs(); /* Line 9 */
((Truth)tellIt).tellItLikeItIs(); /* Line 10 */
}
}
class Tell extends Speak implements Truth {
public void tellItLikeItIs() {
System.out.println("Right on!");
}
}
interface Truth {
public void tellItLikeItIs()
}
Line 7, 8 and 10 are the correct ones. I get number 7, but why isn't number 6 and 9 correct instead of 8 and 10? And how come we can explicitly cast to an interface? what logic is behind the use of parentheses of answer 8 and 10?
回答1:
(Truth) tellIt.tellItLikeItIs()
calls tellItLikeItIs()
on the tellIt
object, and casts the value returned by this method to Truth
.
((Truth) tellIt).tellItLikeItIs()
casts tellIt
to Truth
, and then calls tellItLikeItIs()
on the object.
回答2:
"but why isn't number 6 and 9 correct instead of 8 and 10?"
It's because of operator precedence. Casting is lower then method calling, that's why you have to enfore priorisation of casting by putting it in brackets.
"And how come we can explicitly cast to an interface?"
You say, that an object is now treated like the interfaces says it, regardless of the backing class.
回答3:
The Speak
class has no method tellItLikeItIs
, only the class Tell
and the interface Truth
(which it implements) do.
Line 8 invokes the aforementioned method on a Tell
instance, which is fine. Lines 7 and 10 explicitly cast objects to Truth
, and then invoke the method, which is also OK.
Line 6 and 9 have the same problem - they lack brackets in the correct place. Because of Java's operator priority, they both attempt to invoke the method on some object, and then cast its return value to Truth
. Since the return value of this method is void
, it obviously can't be cast in such a fashion.
来源:https://stackoverflow.com/questions/21918423/explicit-casting-on-objects-with-interface-whats-the-use-of-parentheses