javatypescastingsuperclass

For Java assignment "x=y", does a Java compiler requires that x's declared type is the supertype of y's (including the same type)?


Formulated in another way:

could you give an example assignment of JAVA, x=y, such that the declared type of "x" is not a supertype of that of "y"?

Recall that the declared type is "T" if x is declared as "T x". (supertype includes "the same type" by convention.)


Solution

  • In assignment the LHS must be the type or the RHS or a super type. With supertype also covariant array types are meant: String[] to Object[] (never use that!). Or widening (primitive types) may take place: assigning an int to a float. Or boxing may happen: Integer to int, int to Integer.