Date post: | 11-Feb-2017 |
Category: |
Technology |
Upload: | fraboni-ec |
View: | 27 times |
Download: | 0 times |
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
1
Chapter 8
Polymorphism
Prog
ram
min
g W
ith Ja
vaIC
S 2
01Object-Oriented Concept
Object & Class Encapsulation Inheritance Polymorphism
2
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
3
Polymorphism polymorphism: many forms
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
4
Polymorphism Polymorphism (from the Greek, meaning "many forms", or
something similar) The mechanism by which several methods can have the same
name and implement the same abstract operation. Requires that there be multiple methods of the same name The choice of which one to execute depends on the object
that is in a variable Reduces the need for programmers to code many if-else or
switch statements
Prog
ram
min
g W
ith Ja
vaIC
S 2
01Polymorphism
DrawChart
DrawChart(1)
DrawChart(1,2,1,2)
DrawChart(1,1,1)
DrawTriangle(1,1,1)
DrawRect(1,2,1,2)
DrawCircle(1)
5
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
6
Polymorphism Example
Prog
ram
min
g W
ith Ja
vaIC
S 2
01Polymorphism
Add(integer, integer)Add(string, string)Add(string, integer) Add(1,1) 2 Add(“Hello”, “World”)
“HelloWorld” Add(“Hello”, 2) “Hello2”
Prog
ram
min
g W
ith Ja
vaIC
S 2
01Polymorphism
:PaySlip
:HourlyPaidEmployee
:WeeklyPaidEmployee
:MonthlyPaidEmployee
getTotalPay()
calculatePay()
calculatePay()
calculatePay()
8
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
Which bill() version ?Which bill() version ?
Which bill() versions ?
Introductory example to Polymorphism
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
10
Polymorphism Methods can be overloaded. A method has the same name as
another member methods, but the type and/or the count of parameters differs.
class Integer {
float val;void add( int amount ){val = val + amount; }void add( int num, int den){val = float(num) / den; }
}
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
11
Polymorphism
Polymorphism is the ability to associate many meanings to one method name It does this through a special mechanism known as late
binding or dynamic binding Inheritance allows a base class to be defined, and other
classes derived from it Code for the base class can then be used for its own
objects, as well as objects of any derived classes Polymorphism allows changes to be made to method
definitions in the derived classes.
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
12
Late Binding
The process of associating a method definition with a method invocation is called binding.
If the method definition is associated with its call when the code is compiled, that is called early binding.
If the method definition is associated with its call when the method is invoked (at run time), that is called late
binding or dynamic binding.
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
13
The Sale and DiscountSale Classes
The Sale class contains two instance variables name: the name of an item (String) price: the price of an item (double)
It contains two constructors A no-argument constructor that sets name to "No
name yet", and price to 0.0
A two-parameter constructor that takes in a String (for name) and a double (for price)
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
14
The Sale and DiscountSale Classes The Sale class also has
a set of accessors (getName, getPrice), mutators (setName, setPrice), overridden methods equals and toString a static announcement method. a method bill, that determines the bill for a sale, which
simply returns the price of the item. It has also two methods, equalDeals and lessThan,
each of which compares two sale objects by comparing
their bills and returns a boolean value.
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
15
The Sale and DiscountSale Classes The DiscountSale class inherits the instance variables and
methods from the Sale class. In addition, it has its own instance variable, discount (a
percent of the price), it has also its own suitable constructor methods, accessor method (getDiscount), mutator method (setDiscount), overriden toString method, and static announcement
method. It has also its own bill method which computes the bill as a
function of the discount and the price.
Prog
ram
min
g W
ith Ja
vaIC
S 2
01The Sale and DiscountSale Classes
The Sale class lessThan method Note the bill() method invocations:
public boolean lessThan (Sale otherSale){ if (otherSale == null) { System.out.println("Error:null object"); System.exit(0); } return (bill( ) < otherSale.bill( ));}
Prog
ram
min
g W
ith Ja
vaIC
S 2
01The Sale and DiscountSale Classes
The Sale class bill() method:
public double bill( ) { return price; }
The DiscountSale class bill() method:
public double bill( ) { double fraction = discount/100; return (1 - fraction) * getPrice( ); }
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
18
The Sale and DiscountSale Classes Given the following in a program: . . .Sale simple = new sale(“xx", 10.00);DiscountSale discount = new DiscountSale(“xx", 11.00, 10); . . .if (discount.lessThan(simple)) System.out.println("$" + discount.bill() + " < " + "$" + simple.bill() + " because late-binding works!"); . . .
Output would be:
$9.90 < $10 because late-binding works!
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
19
The Sale and DiscountSale Classes In the previous example, the boolean expression in the if
statement returns true. As the output indicates, when the lessThan method in the
Sale class is executed, it knows which bill() method to invoke The DiscountSale class bill() method for discount,
and the Sale class bill() method for simple. Note that when the Sale class was created and compiled,
the DiscountSale class and its bill() method did not yet exist These results are made possible by late-binding
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
20
The final Modifier A method marked final indicates that it cannot be
overridden with a new definition in a derived class If final, the compiler can use early binding with the
method
public final void someMethod() { . . . }
A class marked final indicates that it cannot be used as a base class from which to derive any other classes
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
21
Upcasting and Downcasting Upcasting is when an object of a derived class is assigned to
a variable of a base class (or any ancestor class):
Example:class Shape {
int xpos, ypos ;public Shape(int x , int y){xpos = x ;ypos = y ;}public void Draw() {System.out.println("Draw method called of class Shape") ;}
}
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
22
Upcasting and Downcastingclass Circle extends Shape {
int r ;public Circle(int x1 , int y1 , int r1){super(x1 , y1) ;r = r1 ;}public void Draw() {System.out.println("Draw method called of class Circle") ;}
}class UpcastingDemo {
public static void main (String [] args) {Shape s = new Circle(10 , 20 , 4) ;s.Draw() ; }
} Output: Draw method called of class Circle
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
23
Upcasting and Downcasting
When we wrote Shape S = new Circle(10 , 20 , 4), we have
cast Circle to the type Shape.
This is possible because Circle has been derived from Shape
From Circle, we are moving up to the object hierarchy to
the type Shape, so we are casting our object “upwards” to
its parent type.
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
24
Upcasting and Downcasting Downcasting is when a type cast is performed from a
base class to a derived class (or from any ancestor class to any descendent class).
Example:class Shape {
int xpos, ypos ;public Shape(int x , int y){xpos = x ;ypos = y ;}public void Draw() {System.out.println("Draw method called of class Shape") ;}
}
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
25
Upcasting and Downcastingclass Circle extends Shape {
int r ;public Circle(int x1 , int y1 , int r1){
super(x1 , y1) ;r = r1 ;
}public void Draw() {
System.out.println("Draw method called of class Circle") ;}
public void Surface() {System.out.println("The surface of the circle is " +((Math.PI)*r*r));
}}
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
26
Upcasting and Downcastingclass DowncastingDemo {
public static void main (String [] args) {
Shape s = new Circle(10 , 20 , 4) ;
((Circle) s).Surface() ; } }
Output: The surface of the circle is 50.26
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
27
Upcasting and Downcasting When we wrote Shape s = new Circle(10 , 20 , 4) we have
cast Circle to the type shape.
In that case, we are only able to use methods found in Shape,
that is, Circle has inherited all the properties and methods of
Shape.
If we want to call Surface() method, we need to down-cast
our type to Circle. In this case, we will move down the
object hierarchy from Shape to Circle : ((Circle) s).Surface() ;
Prog
ram
min
g W
ith Ja
vaIC
S 2
01
28
Downcasting
It is the responsibility of the programmer to use
downcasting only in situations where it makes sense
The compiler does not check to see if downcasting is a
reasonable thing to do
Using downcasting in a situation that does not make sense
usually results in a run-time error.