Java casting order
Suppose I have the following settings
class A { B foo(); } class C extends B { } // later A a = new A(); C theFoo = (C)a.foo();
We know that A. foo () returns type B
When I do (c) A. foo (), right
>How about converting a class to C and then trying to call foo()? > Call foo () and convert the result to class C?
I find it hard to be sure, and I've always just added extra parentheses on the cautious side (it's not a bad idea, readability, but now I'm curious)
This is a specific reference to objectinputstream Readobject(), although I can't see how to change the behavior
Solution
(C) A. foo () is equivalent to (c) (A. foo ()), that is, the #2
To get #1, you must write ((c) a) foo().
The Java language specification does not specify operator precedence in a nice, easy - to - read summary
Introduction to java written by Sedgewick and Wayne appendix a comprehensive table with operator priority
Appendix B of the Java programming language has an operator precedence table, but it is not as complete as Sedgewick
A careful examination of the grammar in the Java language specification can determine the relative priority of the relevant transformation and method call expressions:
Expression: Expression1 [AssignmentOperator Expression1]] Expression1: Expression2 [Expression1Rest] Expression1Rest: ? Expression : Expression1 Expression2 : Expression3 [Expression2Rest] Expression2Rest: {InfixOp Expression3} Expression3 instanceof Type Expression3: PrefixOp Expression3 ( Expression | Type ) Expression3 Primary {Selector} {PostfixOp} Primary: ParExpression NonWildcardTypeArguments (ExplicitGenericInvocationSuffix | this Arguments) this [Arguments] super SuperSuffix Literal new Creator Identifier { . Identifier }[ IdentifierSuffix] BasicType {[]} .class void.class
Make relevant in bold We can see that a conversion expression matches the production expression3: (expression | type) expression3 The method call matches the production expression3: primary {selector} {postfixop} through the production primary: identifier { Identifier} [identifiersuffix] Putting them together, we see that the method call expression will be treated as a unit (an expression3) operated by the actor
Well, the priority map is easier to follow...)