80 likes | 225 Views
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.
E N D
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 Animal goofy = new Dog ( ); Animal trick ( ) ; Dog trick ( ) { dance ( ) } wagTail ( ); goofy.trick ( ) result: animal.trick ( ) VS dog.trick() dog.trick()
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
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 ( ) ; }
public static void train ( Animal a ) { a.trick ( ) ; } Dog trick ( ) { dance ( ) } Elephant trick ( ) { stand ( ) } Tiger Trick ( ) { jump ( ) }
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