Java Reference
In-Depth Information
3.4. Type Compatibility and Conversion
The Java programming language is strongly typed, which means that it
checks for type compatibility at compile time in most casespreventing in-
compatible assignments by forbidding anything questionable. Now that
you understand the basic type relationship defined by subclasses and
superclasses, we can revisit a few details regarding the compatibility of
reference types within assignments (implicit or explicit) and conversion
between types. The full rules for how and when type conversions are ap-
plied, for both reference and primitive types, are discussed in " Type Con-
versions " on page 216 .
3.4.1. Compatibility
When you assign the value of an expression to a variable, either as part
of an initializer, assignment statement, or implicitly when an argument
value is assigned to a method parameter, the type of the expression
must be compatible with the type of the variable. For reference types
this means that the type of the expression must be the same type as,
or a subtype of, the declared type of the variableor can be converted to
such a type. For example, any method that expects an Attr object as a
parameter will accept a ColorAttr object because ColorAttr is a subtype
of Attr . This is called assignment compatibility. [2] But the converse is not
trueyou cannot assign an Attr object to a variable of type ColorAttr , or
pass an Attr object as an argument when a ColorAttr is expected.
[2] There is a slight difference between direct assignment and parameter passingsee the discussion on
page 218 .
The same rule applies for the expression used on a return statement
within a method. The type of the expression must be assignment com-
patible with the declared return type of the method.
The null object reference is a special case in that it is assignment com-
patible with all reference types, including array typesa reference variable
of any type can be assigned null .
 
 
Search WWH ::




Custom Search