Object reference conversion : Reference Type Casting « Type Casting « SCJP






Objects, interfaces, and arrays are "reference" data types. 

Any reference can be cast to the Object.

Object type determines which method is used at runtime.

Reference type determines which overloaded method will be used at compile time.

There are two types of reference variable casting: downcasting and upcasting.

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 downcasting.

Upcasting: You can assign a reference variable to a supertype reference variable explicitly or implicitly. 

Upcasting is an inherently safe operation because the assignment restricts the access 
capabilities of the new variable.

Object reference conversion is permitted when the conversion is towards the top in the 
inheritance hierarchy


public class MainClass {
  public static void main(String[] argv) {
    MyClass myClass = new MyClass();

    MySubclass mySub = new MySubclass();
    mySub = myClass;

    System.out.println();
  }
}

class MyClass {

}

class MySubclass extends MyClass {

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from MyClass to MySubclass

	at MainClass.main(MainClass.java:6)








4.3.Reference Type Casting
4.3.1.Object reference conversion
4.3.2.An interface type can be converted to an interface type or to Object.
4.3.3.Convert interface to super-interface
4.3.4.Object Method-Call Conversion
4.3.5.Cast between an interface and a nonfinal object.
4.3.6.Runtime casting: the class being converted must be itself or must inherit from it.
4.3.7.If New type is an interface, the class of the expression being converted must implement New type.
4.3.8.For = with object references, if the type of the left operand is a class C, then the type of the right operand must be a subclass of C or the null value.
4.3.9.If the type of the left operand is an interface I, the type of the right operand must be a subinterface of I, or a class that implements I, or the null value.
4.3.10.A reference to any object can be cast into a reference to an object of class Object.
4.3.11.A reference to an object can be cast into a reference to an object of its parent class.
4.3.12.A reference to an object can be cast into a reference to an object of its implemented interface
4.3.13.A reference to an object can be cast into a reference to an object of its implemented super interface
4.3.14.Casting Object References with Collections
4.3.15.An Object reference can be converted to:
4.3.16.Use a reference variable to refer to any object that is a subclass of the declared reference variable type