Detailed significance of java downcast

Review the basics of polymorphism:

Polymorphic three requirements:
1. The polymorphism is a polymorphic method, polymorphism is not a property (attribute independent and polymorphism).
2. The presence of polymorphism has three necessary conditions: inherited, override methods, references to the parent class subclasses the object.
3. After the parent class reference to sub-class object, method calls with reference to a subclass overrides the superclass, then multi-state arises.

 

Detailed examples:

Here are inherited, there are ways to rewrite, but the lack of a reference point to the parent class subclass object.

. 1  class AllAnimal {
 2      public  void Speak () {
 . 3          System.out.println ( "We are animals" );
 . 4      }
 . 5  }
 . 6   
. 7  class Cat the extends AllAnimal {    
 . 8      public  void Speak () {
 . 9          System.out.println ( "I am a cat" );
 10      }
 . 11  }
 12 is   
13 is  class fish the extends AllAnimal {
 14      public  void Speak () {
 15          System.out.println ( "I fish");
 16      }    
 . 17      public  void Cando () {
 18 is          System.out.println ( "I can swim" );
 19      }
 20 }

This produces a polymorphic: references to the parent class subclasses the object.

. 1  public  static  void main (String [] args) {
 2          AllAnimal = A new new Cat ();
 . 3          a.speak ();      // I Cat 
4 }

 

The following formal discussions downcast and upcast:

Auto upward transition:

1  // automatic upcast 
2 AllAnimal = A new new Fish ();
 . 3 a.speak ();      // I fish

Here from the compiler's point of view, first of all you need to know compiler is a "fool"! It is considered a AllAnimal, it will first go AllAnimal class find speak () method, this method is found, then compile. (Actually a subclass is directed Cat).

Upcast flaw:

AllAnimal a = new Fish (); 
a.canDo (); // 报错

According to the above mentioned compiler is considered a AllAnimal, it will first go to look for AllAnimal in canDo () method, but did not find a fight, this method is a new method to increase subclass, the compiler will not pass.
 

In order to solve the above problems, the introduction of compulsory downcast:

. 1 AllAnimal = A new new Fish ();
 2  a.speak ();     
 . 3  // forced downward transition 
. 4 Fish A1 = (Fish) A;
 . 5 a1.canDo ();

Thereby obtaining downcast meaning: the use of a new subclass .


Original: https: //blog.csdn.net/qq_41877184/article/details/83052417

Guess you like

Origin www.cnblogs.com/sunzhongyu008/p/11203444.html