The object type conversion referred to here refers to an object that has an inheritance relationship, not an object of any kind. The Java runtime throws a Java.lang.ClassCastException exception when coercion casts on objects that do not have an inheritance relationship.
In the inheritance chain, we convert the subclass to the parent class as "up transformation" and the parent class to the subclass transformation called "down transformation".
Many times, we define a variable as the type of the parent class, but refer to the object of the subclass, which is the process of upward transformation. When the program runs, it implements the invocation of a subclass method by dynamic binding, that is, polymorphism.
Sometimes, however, in order to accomplish something that the parent class does not have, we need to turn the object of the upward transformation into a subclass, calling the method of the subclass, which is the downward transformation.
Note: You cannot cast an object of the parent class directly to a subclass type, but you can only convert the sub-class object that is being transformed to a subclass type again. in other words, the subclass object must be transformed upward before it can be transformed downward. take a look at the following code:
- Public class Demo {
- public static void main(String args[]) {
- Superclass superobj = new superclass();
- sonclass sonobj = new sonclass();
- //The following code runs with an exception and cannot convert the parent object directly to a subclass type
- //Sonclass sonObj2 = (sonclass) superobj;
- //upward transformation, then downward transformation
- Superobj = Sonobj;
- sonclass sonObj1 = (sonclass) superobj;
- }
- }
- Class superclass{ }
- Class Sonclass extends superclass{ }
Remove the comment from line 7th, and the runtime throws an exception, but the compilation can pass.
Because there is a risk of a downward transition, be sure to use the instanceof operator to determine if the object is the subclass you want when you receive a reference to the parent class, see the following code:
- Public class Demo {
- public static void main(String args[]) {
- Superclass superobj = new superclass();
- sonclass sonobj = new sonclass();
- //Superobj not an instance of the Sonclass class
- if(superobj instanceof sonclass){
- sonclass sonObj1 = (sonclass) superobj;
- }Else{
- System. Out. println("① cannot be converted");
- }
- Superobj = Sonobj;
- //Superobj is an instance of the Sonclass class
- if(superobj instanceof sonclass){
- sonclass SonObj2 = (sonclass) superobj;
- }Else{
- System. Out. println("② cannot be converted");
- }
- }
- }
- Class superclass{ }
- Class Sonclass extends superclass{ }
Operation Result:
① cannot be converted
Summary: Object type conversions are checked at program run time, the upward transformation is automatic, and the object that is transitioning down must be a subclass of the current reference type.
Type conversions for 8.Java polymorphic objects