More Polymorphism Labs 7 10 Extra Notes Objective
More Polymorphism Labs 7 -10 Extra Notes Objective: We will exam the rules of polymorphism in relation to creating references/objects and using methods Closing Task: I will be able to identify valid object instantiations and valid method calls for objects.
Review ® We can have a superclass reference a subclass object. ® Example: the explore method: public static void explore(Climber arg) //defined with a Climber reference ® However, when we use explore, we can say: explore( new Hill. Climber(y) ); //will work because Hill. Climber is a subclass of Climber
Review contd. ® When we call the explore method, although the definition includes a Climber reference as an argument, JAVA knows to use Hill. Climber’s methods (JAVA will use Hill. Climber’s climb. Up. Right and not Climber’s) because we sent the method a Hill. Climber object as an actual parameter.
Polymorphism Rules ® It is the type of reference that determines the legality and the type of object that determines the behavior ® We can have a superclass reference a subclass object. Climber bob = new Hill. Climber(1); //VALID ® We cannot have a subclass reference a superclass object. Hill. Climber deb = new Climber(1); //NOT VALID
More Examples ® If an object is defined as follows: ® Climber ® The bob = new Hill. Climber(1); left side is a Climber reference, the right side is actually creating a Hill. Climber object (because the new operator and the Hill. Climber constructor are used).
Legality ® When you have a statement like: ® Climber bob = new Hill. Climber(1); ® The left side (or reference) determines the legality of methods called. ® bob. climb. Up. Left(); //JAVA will first check to see if the Climber class has this method. ® It does, so it is legal
Legality ® When ® Robot you have a statement like: sue = new Athlete(); ® The left side (or reference) determines the legality of methods called. ® sue. turn. Right(); //JAVA will first check to see if the Robot class has this method. ® It does not, so it is illegal
Behavior ® After JAVA verifies it is a legal method ® Climber bob = new Hill. Climber(1); ® The right side (or object) determines the behavior ® bob. climb. Up. Left(); //JAVA will implement the Hill. Climber’s climb. Up. Left method. ® Racer ron = new Box. Top. Racer(1); ® ron. jump. Right(); ® Legal? YES Whose behavior? Box. Top. Racer
Behavior ® Robot sue = new Athlete(); ® sue. turn. Right(); ® Legal Method? NO ® Robot Whose behavior? NO ONE sue = new Athlete(); ® sue. turn. Left(); ® Legal? YES Whose behavior? Robot, by default…checks Athlete first. Since Athlete doesn’t override
- Slides: 9