Java polymorphism
Download
Report
Transcript Java polymorphism
Outline
Review of the last class
class variables and methods
method overloading and overriding
Inheritance and polymorphism
polymorphism
abstract classes and interface
class Circle {
• public static final double PI = 3.14159;
• public double x, y, r;
}
public class example{
• public static void main(String[] args){
• Circle.PI = 4;
•}
}
Is this correct?
class variable
class Circle {
• public static final double PI = 3.14159;
• public double x, y, r;
}
public class example{
• public static void main(String[] args){
• Circle.PI = 4;
//Error
•}
}
The final keyword means that this variable can never be
changed.
public class Circle {
public double x, y, r;
// an class method. Returns the bigger of two circles.
public static Circle bigger(Circle c){
if(c.r > r)
return c;
else
return this;
}
//other methods omitted here.
}
Is this correct?
class method
public class Circle {
public double x, y, r;
// an class method. Returns the bigger of two circles.
public static Circle bigger(Circle c){
if(c.r > r)
//Error
return c;
else
return this;
//Error
}
}
static methods may not manipulate any
instance variables!
Method Overloading and Overriding
What is the difference?
Overloading and Overriding
What is the difference?
Overloading
several methods of the same name can be
defined, as long as the methods have different
sets of parameters
Overriding
a subclass can redefine a superclass method by
using the same signature
Overloading
public class Overload {
// first definition of method square
public int square(double x){
return x * x;
}
// second definition of method square
public double square(double y){
return y * y;
}
} //end class Overload
Is this correct?
Overloading
public class Overload {
// first definition of method square with double argument
public int square(double x){
return x * x;
}
// second definition of method square with double argument
// causes syntax error
public double square(double y){
return y * y;
}
} //end class Overload
The compiler would not know how to
distinguish between the two square methods.
Overloading
Overloading methods are distinguished by
their signature -- a combination of the
method’s name and its parameter types
Methods can not be distinguished by return
type
Creating overloaded methods with identical
parameters lists and different return types is
a syntax error
Overloading and overriding
A redefinition of a superclass method in a
subclass need not have the same signature
as the superclass method. Such a
redefinition is not method overriding; rather
it is an example of overloading.
It is syntax error if a method in a superclass
and a method in a subclass have the same
signature but a different return type.
Shape Classes
We have a class called Shape
assume all shapes have x and y coordinates
override Object's version of toString
Two subclasses of Shape
Rectangle add a new method changeWidth
Circle
A Shape class
public class Shape
{ private double dMyX, dMyY;
public Shape() {
this(0,0);}
public Shape (double x, double y)
{ dMyX = x;
dMyY = y;
}
public String toString()
{ return "x: " + dMyX + " y: " + dMyY;
}
public double getArea() {
return 0;
}
}
A Rectangle Class
public class Rect extends Shape
{ private double dMyWidth, dMyHeight;
public Rect(double width, double height)
{ dMyWidth = width;
dMyHeight = height;
}
public String toString()
{ return
" width " + dMyWidth
+ " height " + dMyHeight;
}
public double getArea() {
return dMyWidth * dMyHeight;
}
public void changeWidth(double width){
dMyWidth = width;
}
}
A Circle Class
class Circle extends Shape {
private double radius;
private static final double PI = 3.14159;
public Circle(double rad){
radius = rad;
}
public double getArea() {
return PI * radius * radius;
}
public String toString() {
return " radius " + radius;
}
}
Polymorphism
If class Rect is derived from class Shape, an
operation that can be performed on an object
of class Shape can also be performed on an
object of class Rect
When a request is made through a superclass
reference to use a method, Java choose the
correct overridden method polymorphically in
the appropriate subclass associated with the
object
Polymorphism means “different forms”
Object Variables
Rect r = new Rect(10, 20);
Shape s = r;
System.out.println("Area is " +
s.getArea());
Assume class Rect is a subclass of class
Shape, and it overrides the method
getArea().
Does this work?
Object Variables
Rect r = new Rect(10, 20);
Shape s = r;
System.out.println("Area is " + s.getArea());
The above code works if Rect extends Shape
An object variable may point to an object of its
base type or a descendant in the inheritance chain
The is-a relationship is met. A Rect is-a shape so s may
point to it
This is a form of polymorphism and is used
extensively in the Java Collection classes
Vector, ArrayList are lists of Objects
More Polymorphism
Circle c = new Circle(5);
Rect r = new Rect(5, 3);
Shape s = null;
if( Math.random(100) % 2 == 0 )
s = c;
else
s = r;
System.out.println( "Shape is "
+ s.toString() );
Assuming Circle and Rect are subclasses of
Shape, and have both overridden toString(),
which version gets called?
More Polymorphism
Circle c = new Circle(5);
Rect r = new Rect(5, 3);
Shape s = null;
if( Math.random(100) % 2 == 0 )
s = c;
else
s = r;
System.out.println( "Shape is "
+ s.toString() );
Assuming Circle and Rect have both overridden
toString which version gets called?
code works because s is polymorphic
method call determined at run time by dynamic binding
Type Compatibility
Rect r = new Rect(5, 10);
Shape s = r;
s.changeWidth(20);
Assume class Rect is a subclass of class
Shape, and it has a new method
changeWidth(double width), which its super
class does not have.
Does this work?
Type Compatibility
Rect r = new Rect(5, 10);
Shape s = r;
s.changeWidth(20); // syntax error
polymorphism allows s to point at a Rect object
but there are limitations
The above code does not work
How can you modify it a little to make it work
without changing the classes definitions?
Type Compatibility
Rect r = new Rect(5, 10);
Shape s = r;
s.changeWidth(20); // syntax error
polymorphism allows s to point at a Rect object but there
are limitations
The above code does not work
Statically s is declared to be a shape
no changeWidth method in Shape class
must cast s to a rectangle;
Rect r = new Rect(5, 10);
Shape s = r;
((Rect)s).changeWidth(20); //Okay
Problems with Casting
Rect r = new Rect(5, 10);
Circle c = new Circle(5);
Shape s = c;
((Rect)s).changeWidth(4);
Does this work?
Problems with Casting
The following code compiles but an exception
is thrown at runtime
Rect r = new Rect(5, 10);
Circle c = new Circle(5);
Shape s = c;
((Rect)s).changeWidth(4);
Casting must be done carefully and correctly
If unsure of what type object will be then use
the instanceof operator
instanceof
Rect r = new Rect(5, 10);
Circle c = new Circle(5);
Shape s = c;
if(s instanceof Rect)
((Rect)s).changeWidth(4);
syntax: expression instanceof ClassName
instanceof example
(syntax: expression instanceof ClassName)
Assume Manual is a Book, and Book is a Publication. Output?
public class InstanceofDemo {
public static void main(String args[]) {
Publication pub1 = new Publication();
Book book1 = new Book();
Manual manual1 = new Manual();
if (pub1 instanceof Book)
System.out.println(“pub1 is a Book”);
if (book1 instanceof Book)
System.out.println(“book1 is a Book”);
if (manual1 instanceof Book)
System.out.println(“manual1 is a Book”);
}
}
Casting
It is always possible to convert a subclass to a
superclass. For this reason, explicit casting can be
omitted. For example,
Circle c1 = new Circle(5);
Shape s = c1;
is equivalent to
Shape s = (Shape)c1;
Explicit casting must be used when casting an
object from a superclass to a subclass. This type
of casting may not always succeed.
Circle c2 = (Circle) s;
Implicit Subclass-Object-to-SuperclassObject Conversion
Four possible ways to mix and match superclass
references and subclass references with superclass
objects and subclass objects
refer to a superclass object with a superclass reference
refer to a subclass object with a subclass reference
referring to a subclass object with a superclass
reference is safe, but such code can only refer to
superclass members
referring to a superclass object with a subclass
reference is a syntax error
The role of final in Inheritance
A class may be declared as final
that class may not be extended
A method in a class may be declared as final
that method may not be overridden
guarantees behavior in all descendants
can speed up a program by allowing static binding
(binding or determination at compile time what
code will actually be executed)
All static methods and private methods are
implicitly final, as are all methods of a final
class.
Abstract Classes and Methods
An abstract class defines a common interface
for the various members of a class hierarchy.
an object of that type never exists and can never be
instantiated.
a Shape or a Mammal
a method may be declared abstract in its
header, after visibility modifier
no body to the method
all derived classes must eventually implement this
method (or they must be abstract as well)
any class with 1 or more abstract methods must be
an abstract class
abstract class Shape {
public Shape() {
id = ++count;
}
public int getId() {
return id;
}
public abstract double getArea();
private static int count = 0;
private int id;
}
class Rectangle extends Shape {
public Rectangle(int ul_x, int ul_y, int lr_x, int lr_y) {
upperLeft = new Point(ul_x, ul_y);
lowerRight = new Point(lr_x, lr_y);
}
public double getArea() {
double result = Math.abs(upperLeft.x - lowerRight.x)
* Math.abs(upperLeft.y - lowerRight.y);
return result;
}
private Point upperLeft;
private Point lowerRight;
}
import java.awt.Point;
class Circle extends Shape {
public Circle(int x, int y, int rad) {
center = new Point(x, y);
radius = rad;
}
public double getArea() {
return 4 * Math.atan(1.0) * radius * radius;
// pi == 4 * atan(1.0)
}
private int radius;
private Point center;
}
Genericity
One of the goals of OOP is the support of
code reuse to allow more efficient program
development
If an algorithm is essentially the same, but
the code would vary based on the data type
genericity allows only a single version of
that code to exist
some languages support genericity via
templates
in Java, polymorphism and the inheritance
requirement along with interfaces are used
Multiple Inheritance
Inheritance models the "is-a" relationship
between real world things
one of the benefits is code reuse, completing
programs faster, with less effort
in the real world a thing can have "is-a"
relationships with several other things
a Graduate Teaching Assistant is-a Graduate
Student. Graduate Teaching Assistant is-a
Employee
a Student is-a Person. a Student is a
SortableObject
Interfaces
A Java interface is a "pure abstract
class".
Design only, no implementation.
Interfaces are declared in a way similar to
classes but
consist only of public abstract methods
public final fields
A Java class extends exactly one other class,
but can implement as many interfaces as
desired
Common Interfaces in Java
One of the most interesting interfaces is:
Comparable
package java.lang
public interface Comparable
{
public int compareTo( Object other );
}
compareTo should return an int <0 if the calling object is
less than the parameter, 0 if they are equal, and an int >0 if
the calling object is greater than the parameter
Implementing an Interface
public class Card implements Comparable{
public int compareTo(Object otherObject){
Card other = (Card)otherObject;
int result = mySuit - other.mySuit;
if(result == 0)
result = myValue - other.myValue;
return result;
}
// other methods not shown
}
If a class declares that it will implement an interface, but
does not provide an implementation of all the methods in
that interface, that class must be abstract
Polymorphism Again
public static sort(Comparable[] list)
{ Comparable temp;
int smallest;
for(int i = 0; i < list.length - 1; i++)
{ small = i;
for(int j = i + 1; j < list.length; j++)
{ if( list[j].compareTo(list[small]) < 0)
small = j;
} // end of j loop
temp = list[i];
list[i] = list[small];
list[small] = temp;
} // end of i loop
}