0% found this document useful (0 votes)
25 views

Chapter 5-Polymor

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter 5-Polymor

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Polymorphism

1
Polymorphism
 Inheritance allows you to define a base class and derive classes
from the base class
 Polymorphism: ability for the same code to be used with
different types of objects and behave differently with each.
 Ability of an object to execute specialized actions based on its type
 Inheritance is one in which a new class is created; polymorphism is
that which can be defined in multiple forms
 Polymorphism is a Greek word meaning “many forms”.
 Example: Suppose we create a program that simulates the
movement of several types of animals for a biological study.
 Classes Fish, Frog and Bird represent the three types of animals
under investigation.
 Each class extends superclass Animal, which contains a
method move and maintains an animal’s current location as
x-y coordinates.
 To simulate the animals’ movements, the program sends each
object the same message once per second. 2
Polymorphism(cont’d)
 However, each specific type of Animal responds to a move message
in a unique way
 a Fish might swim three feet, a Frog might jump five feet and a
Bird might fly ten feet.
 The program issues the same message (i.e., move ) to each animal
object generically, but each object knows how to modify its x-y
coordinates appropriately for its specific type of movement.
 Relying on each object to know how to “do the right thing” in
response to the same method call is the key concept of
polymorphism.
 The same message (in this case, move) sent to a variety of objects
has “many forms” of results — hence the term polymorphism.
 Late binding(dynamic binding): the process of associating a
method definition with a method invocation at run-time
 Static binding(early binding) bind at compilation time
3
Polymorphism(cont’d)
 Polymorphism and late binding are essentially just different
words for the same concept
 Polymorphism refers to the processes of assigning multiple
meanings to the same method name using late binding
 With polymorphism, we can design and implement systems
that are easily extensible
 New classes can be added with little or no modification to the
general portions of the program, as long as the new classes are part
of the inheritance hierarchy that the program processes generically.
 The only parts of a program that must be altered to accommodate
new classes are those that require direct knowledge of the new
classes that we add to the hierarchy.

4
Polymorphism Example
 Example: Quadrilaterals
 If Rectangle is derived from Quadrilateral, then a Rectangle
object is a more specific version of a Quadrilateral.
 Any operation that can be performed on a Quadrilateral can
also be performed on a Rectangle.
 These operations can also be performed on other
Quadrilaterals, such as Squares, Parallelograms and
Trapezoids.
 Polymorphism occurs when a program invokes a method
through a superclass Quadrilateral variable—at execution
time, the correct subclass version of the method is called,
based on the type of the reference stored in the superclass
variable.

5
Polymorphic Behavior
 All Java objects are polymorphic since any object will pass the
IS-A test for at least their own type and the class Object
 A bird is an instance of Bird class, also an instance of Animal and
Object
 We are able to assign an object of a sub-class into an object
of a super-class as in:
 Animal MyAnimal = new Dog();
 But the reverse is not true. We can’t assign a superclass
object into a sub-class object.
 Dog MyDog = new Animal(); // illegal
 All dogs are animals but not all animals are dogs

6
Cont’d

7
Method Calls and Polymorphism
 When a superclass variable contains a reference to a
subclass object, and that reference is used to call a
method, the subclass version of the method is called.
 Assume the Dog class extends the Animal class,
redefining the “makeNoise” method.
 Consider the following:
 Animal myAnimal = new Dog();
 myAnimal.makeNoise();

 Note: The Animal reference is referring to a Dog


object. And it is the Dog’s makeNoise method that
gets invoked!

8
Cont’d
 No matter what the reference type is, Java will search
the object and execute the lowest occurrence of a
method it finds.
 class Object has a toString method
 Assume that both Animal and Dog have overridden
the toString method

9
Downcasting and Upcasting
 Upcasting: assigning an object of a derived class to a
variable of a base class (or any ancestor class).
 E.g. Object o = new Student();

 Downcast: cast from a base case to a derived class


(or from any ancestor class to any descendent class).
 used to restore an object back to its original class (back to
what it was “born as” with the new operator)
 E.g. Student b = (Student)o;

10
Example
 The following two output statements will produce different
results, depending on whether p is a Dog or a Cat:
Pet p;
p = new Dog( );
System.out.println(p.speak( ));
p = new Cat( );
System.out.println(p.speak( ));
 Here the speak method is called a polymorphic method.

11
Example(cont’d)
class Pet {
private String name;
public String getName( ) {
return name;
}
public void setName(String petName) {
name = petName;
}
public String speak( ) {
return "I'm your cuddly little pet.";
}
}
class Cat extends Pet {
public String speak( ) {
return "Don't give me orders.\n" + "I speak only when I want to.";
}
}

12
Example(cont’d)
class Dog extends Pet {
public String fetch( ) {
return "Yes, master. Fetch I will.";
}
}
===============================
public class RunPetDog{
public static void main(String args[]){
Pet p;
p = new Dog( );
System.out.println(p.speak( ));
p = new Cat( );
System.out.println(p.speak( ));

}
}
13
Example(cont’d)
 Output
I’m Your cuddly little pet
Don’t give me orders
I speak only when I want

14
Activity 1
 Assuming SavingsAccount is a subclass of BankAccount, which of
the following code fragments are valid in Java?
a. BankAccount account = new SavingsAccount();
b. SavingsAccount account2 = new BankAccount();
c. BankAccount account = null;
d. SavingsAccount account2 = account;
 Answer: a only.

15
Activity 2
 If account is a variable of type BankAccount that holds
a non-null reference, what do you know about the
object to which account refers?
 Answer: It belongs to the class BankAccount or one
of its subclasses.

16
Activity 3
public class Foo {
public void method1() {
System.out.println("foo 1");
}
public void method2() {
System.out.println("foo 2");
}
public String toString() {
return "foo";
}
}

17
Activity 3(cont’d)
class Bar extends Foo {
public void method2() {
System.out.println("bar 2");
}
}
class Baz extends Foo {
public void method1() {
System.out.println("baz 1");
}
public String toString() {
return "baz";
}
}
class Mumble extends Baz {
public void method2() {
System.out.println("mumble 2");
}
} 18
Activity 4
What is output by the public class Animal{
code to the right when public String bt(){ return "!"; }
}
run?
public class Mammal extends Animal{
A. !!live public String bt(){ return "live"; }
}
B. !eggegg
public class Platypus extends Mammal{
C. !egglive public String bt(){ return "egg";}
}
D. !!!
Animal a1 = new Animal();
E. eggegglive Animal a2 = new Platypus();
Mammal m1 = new Platypus();
System.out.print( a1.bt() );
System.out.print( a2.bt() );
System.out.print( m1.bt() );

19
Polymorphism vs. Inheritance
 Inheritance is required in order to achieve polymorphism
(we must have class hierarchies).
 Re-using class definitions via extension and redefinition

 Polymorphism is not required in order to achieve


inheritance.
 An object of class A acts as an object of class B (an ancestor to A)

20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy