What makes an object assignment-compatible with another class?

前端 未结 5 1375
借酒劲吻你
借酒劲吻你 2021-01-15 01:43

I\'m wondering what specifically allows an object of one class to be cast as another class. Looking at the Class.isInstance(Object obj) javadoc, it suggests that an object

5条回答
  •  既然无缘
    2021-01-15 02:16

    Just wanted to add the official specification to support Ricardo's correct answer that "you can assign an object of type A to variable of type B if type A extends or implements type B":

    The JLS defines assignment-compatibility as follows:

    5.2. Assignment Contexts

    If the type of an expression can be converted to the type of a variable by assignment conversion, we say the expression (or its value) is assignable to the variable or, equivalently, that the type of the expression is assignment compatible with the type of the variable.

    The term "assingment conversion" is only defined as applying the appropriate conversion from the list given in the "Assignment Contexts"-chapter:

    The term "conversion" is also used to describe, without being specific, any conversions allowed in a particular context. For example, we say that an expression that is the initializer of a local variable is subject to "assignment conversion", meaning that a specific conversion will be implicitly chosen for that expression according to the rules for the assignment context.

    The most relevant for reference types being

    5.1.5. Widening Reference Conversion

    A widening reference conversion exists from any reference type S to any reference type T, provided S is a subtype of T (§4.10).

    Subtypes include implemented interfaces (see 4.10.2. Subtyping among Class and Interface Types ).

    There are additional rules for numeric and generic types, but they are not relevant for the example given in the question.

提交回复
热议问题