1 / 8

Andrew Cohen & Jiyeon Lee

Andrew Cohen & Jiyeon Lee. Dance!. Stand!. Jump!. Animal. Animal trick ( ) ;. Dog trick ( ) { dance ( ) } wagTail ( ) {};. Elephant trick ( ) { stand ( ) }. Tiger trick ( ) { jump ( ) }. Then checks for more specific dog.trick (). checks with animal.trick () first !. Animal.

oakley
Download Presentation

Andrew Cohen & Jiyeon Lee

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Andrew Cohen & Jiyeon Lee

  2. Dance! Stand! Jump!

  3. Animal Animal trick ( ) ; Dog trick ( ) { dance ( ) } wagTail ( ) {}; Elephant trick ( ) { stand ( ) } Tiger trick ( ) { jump ( ) }

  4. Then checks for more specific dog.trick () checks with animal.trick () first ! Animal Animal goofy = new Dog ( ); Animal trick ( ) ; Dog trick ( ) { dance ( ) } wagTail ( ); goofy.trick ( ) result: animal.trick ( ) VS dog.trick() dog.trick()

  5. NO wagTail ( ) Looks for wagTail ( ) in Animal class Animal Animal goofy = new Dog ( ); Animal trick ( ) ; Dog trick ( ) { dance ( ) } wagTail ( ); goofy.wagTail ( ) result: COMPILE-TIME ERROR

  6. Upcast all dog, elephant and tiger to Animal in Animal [] circusAnimal. Animal [ ] circusAnimal = [ ] , , Animal Animal Animal Send them to training one by one. for ( Animal a : circusAnimal ) { train ( a ) ; } train ( Animal a ) takes circusAnimal as Animal a one by one and calls trick ( ). public static void train ( Animal a ) { a.trick ( ) ; }

  7. public static void train ( Animal a ) { a.trick ( ) ; } Dog trick ( ) { dance ( ) } Elephant trick ( ) { stand ( ) } Tiger Trick ( ) { jump ( ) }

  8. Polymorphism review • By upcasting your object initializations, you can write methods to accept the super-type object, and they will automatically recognize the precise object sub-type that is dynamically provided as an argument. AS LONG AS: • The method name is exactly the same in the base class and the derived class • The method that is overridden is public

More Related