Java rules for casting

In Java there are two types of reference variable casting:

  • Downcasting: If you have a reference
    variable that refers to a subtype
    object, you can assign it to a
    reference variable of the subtype.
    You must make an explicit cast to do
    this, and the result is that you can
    access the subtype’s members with
    this new reference variable.

  • Upcasting: You can assign a reference
    variable to a supertype reference
    variable explicitly or implicitly.
    This is an inherently safe operation
    because the assignment restricts the
    access capabilities of the new
    variable.

Yes, you need to implement the interface directly or indirectly to enable assigning your class object reference to the interface type.

Leave a Comment