Java parent class coercion subclass principle

Reprinted from  Java Parent Class Coercion Subclass Principle

Recently, WeChat group friends are discussing the conversion of subclass and parent class. In fact, it is not difficult. It is very clear to explain it with an example.

We know that there is no problem in converting a subclass into a parent class in Java. Can a parent class be converted into a subclass?

Take a look at the following program:

publicclassTestObjectConvert{publicstaticvoid main(String[] args){
        test1();
        test2();}privatestaticvoid test1(){Fruit fruit1 =newFruit();Apple apple1 =newApple();
        apple1 =(Apple) fruit1;// java.lang.ClassCastException}private   

       
    

       
          
            
    

     staticvoid test2(){Fruit fruit1 =newApple();Apple apple1 =newApple();
        apple1 =(Apple) fruit1;}staticclassFruit{}staticclassAppleextendsFruit{}}  
          
           
    

       

    

         

    

turn out:

test1 : report class conversion exception; 
test2 : normal conversion.

Therefore, it is not impossible to force the parent class to be converted into a subclass. Unless the parent class is an instance constructed by the subclass, it cannot be forced.

why?

As in the above code, if the object from the parent class instance is Orange, of course Orange cannot be forced to be converted to Apple, so only the instance corresponding to the subclass of the parent class can be forced to be converted.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852831&siteId=291194637