lect13supp

advertisement
CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101x/
Lecture 13: Inheritance and
Polymorphism
 Explore the role of inheritance in object-oriented design.
 Demonstrate the power of polymorphism and the late





binding of methods.
Develop a series of classes demonstrating the power of
the inheritance and polymorphism mechanism.
Explore the nuances of superclasses and subclasses in
Java.
Consider the roles of protected access and default access
in information hiding.
Introduce abstract classes and interfaces.
Provides an appreciation for the use of modifier final with
classes and methods.
Acknowledgement: Cohoon and Davidson.
2
ThreeDimensionalPoint

Build a new class ThreeDimensionalPoint using
inheritance


ThreeDimensionalPoint extends the awt class Point
 Point is the superclass (base class)
 ThreeDimensionalPoint is the subclass (derived class)
ThreeDimensionalPoint extends Point by adding a new
property to Point — a z-coordinate
y-axis
z-axis
(x, y, z)
x-axis
3
Point (1/2)
Data fields:
public int x; // x-coordinate
public int y; // y-coordinate
Constructors:
Point()
Point(int x, int y)
Point(Point p)
// constructs point at (0,0)
// constructs point at (x,y)
// constructs point at location p
Methods:
double getX()
// returns x-coordinate
double getY()
// returns y-coordinate
translate(int dx, int dy)
// translate this point by dx along the x-axis
// and dy along the y-axis
See API specification for complete information:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Point.html
4
Point (2/2)
import java.awt.Point;
public class PointDemo {
public static void main(String[] args) {
Point p = new Point(2,3);
System.out.println(p);
p.translate(10,12);
System.out.println("After translation:");
System.out.println(p);
}
}
+
5
Class ThreeDimensionalPoint
package Geometry;
import java.awt.*;
See next slide.
Keyword ‘extends’ indicates
that ThreeDimensionalPoint
is a subclass of Point.
public class ThreeDimensionalPoint extends Point {
// private class constant
private final static int DEFAULT_Z = 0;
// instance variable
public int z = DEFAULT_Z;
Exception for Point.
New instance variable.
6
Using ThreeDimensionalPoint (1/2)
ThreeDimensionalPoint a =
new ThreeDimensionalPoint(6, 21, 54);
a.translate(1, 1);
// invocation of superclass translate()
a.translate(2, 2, 2); // invocation of subclass translate()



Java determines which method to use based on the
number of parameters in the invocation
After the first call to translate, what is the value of a?
After the second call to translate, what is the value of a?
7
Using ThreeDimensionalPoint (2/2)

Methods toString(), equals() , and clone()
should not have different signatures from the Point
versions
ThreeDimensionalPoint c = new ThreeDImensionalPoint(1, 4, 9);
ThreeDimensionalPoint d = (ThreeDimensionalPoint) c.clone();
Cast is necessary as
return type of subclass
method clone() is Object.
String s = c.toString();
boolean b = c.equals(d);
Invocation of subclass
toString() method.
Invocation of subclass
equals() method.
8
Defining ThreeDimensionalPoint (1/7)
package Geometry;
import java.awt.*;
public class ThreeDimensionalPoint extends Point {
// private class constant
private final static int DEFAULT_Z = 0;
// instance variable
public int z = DEFAULT_Z;
9
Defining ThreeDimensionalPoint (2/7)

Constructors
// ThreeDimensionalPoint(): default constructor
public ThreeDimensionalPoint() {
super();
}
// ThreeDimensionalPoint(): specific constructor
public ThreeDimensionalPoint(int a, int b, int c) {
super(a, b);
setZ(c);
}
10
Defining ThreeDimensionalPoint (3/7)

Accessors and mutators
// getZ(): z-coordinate accessor
public double getZ() {
return z;
}
// setZ(): y-coordinate mutator
public void setZ(int value) {
z = value;
}
11
Defining ThreeDimensionalPoint (4/7)

translate()
// translate(): shifting method
public void translate(int dx, int dy, int dz) {
translate(dx, dy);
int zValue = (int) getZ();
setZ(zValue + dz);
}
12
Defining ThreeDimensionalPoint (5/7)

toString()
// toString(): string representation method
public String toString() {
int a = (int) getX();
int b = (int) getY();
int c = (int) getZ();
return getClass() +
"[" + a + ", " + b + ", " + c + "]";
}
13
Defining ThreeDimensionalPoint (6/7)

equals()
// equals(): equality method
public boolean equals(Object v) {
if (v instanceof ThreeDimensionalPoint) {
ThreeDimensionalPoint p =
(ThreeDimensionalPoint) v;
int z1 = (int) this.getZ();
int z2 = (int) p.getZ();
return super.equals(p) && (z1 == z2);
}
else
return false;
}
14
Defining ThreeDimensionalPoint (7/7)

clone()
// clone(): clone method
public Object clone() {
int a = (int) getX();
int b = (int) getY();
int c = (int) getZ();
return new ThreeDimensionalPoint(a, b, c);
}
15
ThreeDimensionalPoint Demo
public static void main(String[] args) {
ThreeDimensonalPoint p =
new ThreeDimensionalPoint(2, 3, 8);
System.out.println(p);
p.translate(1, 2, 3);
System.out.println("After translation:");
System.out.println(p);
}
+
16
ColoredPoint (1/6)



Suppose an application calls for the use of colored
points.
We can naturally extend class Point to create
ColoredPoint.
Class ColoredPoint will be added to package Geometry.
package Geometry;
import java.awt.*;
public class ColoredPoint extends Point {
// instance variable
Color color;
. . .
17
ColoredPoint (2/6)

Constructors
// ColoredPoint(): default constructor
public ColoredPoint() {
super();
setColor(Color.BLUE);
}
// ColoredPoint(): specific constructor
public ColoredPoint(int x, int y, Color c) {
super(x, y);
setColor(c);
}
18
ColoredPoint (3/6)

Accessors and mutators
// getColor(): color property accessor
public Color getColor() {
return color;
}
// setColor(): color property mutator
public void setColor(Color c) {
color = c;
}
19
ColoredPoint (4/6)

clone()
// clone(): clone method
public Object clone() {
int a = (int) getX();
int b = (int) getY();
Color c = getColor();
return new ColoredPoint(a, b, c);
}
20
ColoredPoint (5/6)

toString()
// toString(): string representation method
public String toString() {
int a = (int) getX();
int b = (int) getY();
Color c = getColor();
return getClass() +
"[" + a + ", " + b + ", " + c + "]";
}
21
ColoredPoint (6/6)

equals()
// equals(): equality method
public boolean equals(Object v) {
if (v instanceof ColoredPoint) {
Color c1 = this.getColor();
Color c2 = ((ColoredPoint) v).getColor();
return super.equals(v) && c1.equals(c2);
}
else
return false;
}
22
ColoredPoint Demo
public static void main(String[] args) {
ColoredPoint p =
new ColoredPoint(6, 2, Color.RED);
System.out.println(p);
p.translate(3, 1);
p.setColor(Color.GREEN);
System.out.println("Updated point:");
System.out.println(p);
}
+
23
Colored3DPoint (1/6)


Suppose an application needs a colored, threedimensional point.
Can we create such a class by extending both
ThreeDimensionalPoint and ColoredPoint?


No. Java does not support multiple inheritance
Java only supports single inheritance
package Geometry;
import java.awt.*;
public class Colored3DPoint extends ThreeDimensionalPoint {
// instance variable
Color color;
. . .
24
Colored3DPoint (2/6)

Constructors
// Colored3DPoint(): default constructor
public Colored3DPoint() {
setColor(Color.BLUE);
}
// Colored3DPoint(): specific constructor
public Colored3DPoint(int a, int b, int c,
Color d) {
super(a, b, c);
setColor(d);
}
25
Colored3DPoint (3/6)

Accessors and mutators
// getColor(): color property accessor
public Color getColor() {
return color;
}
// setColor(): color property mutator
public void setColor(Color c) {
color = c;
}
26
Colored3DPoint (4/6)

clone()
// clone(): clone method
public Object clone() {
int a = (int) getX();
int b = (int) getY();
int c = (int) getZ();
Color d = getColor();
return new Colored3DPoint(a, b, c, d);
}
27
Colored3DPoint (5/6)

toString()
// toString(): string representation method
public String toString() {
int a = (int) getX();
int b = (int) getY();
int c = (int) getZ();
Color d = getColor();
return getClass() + "[" + a + ", " + b +
", " + c + ", " + d + "]";
}
28
Colored3DPoint (6/6)

equals()
// equals(): equality facilitator
public boolean equals(Object v) {
if (v instanceof Colored3DPoint) {
Color c1 = this.getColor();
Color c2 = ((Colored3DPoint) v).getColor();
return super.equals(v) && c1.equals(c2);
}
else
return false;
}
29
Break
Abstract classes and Interfaces – 10
minutes
 Term Test Questions

30
Abstract base classes (1/5)


Allows creation of classes with methods that correspond
to an abstract concept (i.e., there is not an
implementation)
Suppose we wanted to create a class GeometricObject




Reasonable concrete methods include
 getPosition()
 setPosition()
 getColor()
 setColor()
 paint()
For all but paint(), we can create implementations.
For paint(), we must know what kind of object is to be painted.
Is it a square, a triangle, etc.
Method paint() should be an abstract method
31
Abstract base classes (2/5)
Example
import java.awt.*;
Makes GeometricObject
an abstract class.
abstract public class GeometricObject {
// instance variables
Point position;
Color color;
// getPosition(): return object position
public Point getPosition() {
return position;
}
// setPosition(): update object position
public void setPosition(Point p) {
position = p;
}
32
Abstract base classes (3/5)
Example (continued)
// getColor(): return object color
public Color getColor() {
return color;
}
// setColor(): update object color
public void setColor(Color c) {
color = c;
}
// paint(): render the shape to graphics context g
abstract public void paint(Graphics g);
}
Indicates that an implementation of
method paint() will not be supplied.
33
Abstract base classes (4/5)

Subclass Box
import java.awt.*;
public class Box extends GeometricObject {
int length, height;
public Box() {
this(0, 0, new Point(), Color.BLACK);
}
. . .
public void paint(Graphics g) {
Point p = getPosition();
Color c = getColor();
int
l = getLength();
int
h = getHeight();
g.setColor(c);
g.fillRect((int) p.getX(), (int) p.getY(), l, h);
}
}
34
Abstract base classes (5/5)

Subclass Circle
import java.awt.*;
public class Circle extends GeometricObject {
int radius;
public Circle() {
this(0, new Point(), Color.BLACK);
}
. . .
public void paint(Graphics g) {
Point p = getPosition();
Color c = getColor();
int
r = getRadius();
g.setColor(c);
g.fillOval((int) p.getX(), (int) p.getY(), r, r);
}
}
35
Interfaces (1/5)

An interface is a template that specifies what must be in a
class that implements the interface




An interface cannot specify any method implementations
All the methods of an interface are public
All the variables defined in an interface are public, final,
and static
Why use an interface when an abstract class offers
greater flexibility?


A class can implement more than one interface, whereas a class
can extend only one superclass.
As an interface is not a class, it is not part of the class hierarchy.
Hence, two unrelated classes can implement the same interface
with objects of those unrelated classes having the same type –
the interface their class types implements.
36
Interfaces (2/5)

An interface for a colorable object
package geometry;
import java.awt.*;
public interface Colorable {
// getColor(): return the color of the object
public Color getColor();
// setColor(): set the color of the object
public void setColor(Color c);
}
37
Interfaces (3/5)


Now the interface can be used to create classes that
implement the interface
ColorablePoint
import java.awt.*;
public class ColorablePoint extends Point
implements Colorable {
// instance variable
Color color;
// ColorablePoint(): default constructor
public ColorablePoint() {
super();
setColor(Color.blue);
}
. . .
38
Interfaces (4/5)

Colorable3DPoint
import java.awt.*;
public class Colorable3DPoint
extends ThreeDimensionalPoint
implements Colorable {
// instance variable
Color color;
// Colorable3DPoint(): default constructor
public Colorable3DPoint() {
super();
setColor(Color.blue);
}
. . .
39
Interfaces (5/5)

As both ColorablePoint and Colorable3DPoint indicate
they implement interface Colorable, a polymorphic code
segment such as this is possible.
ColorablePoint u = new ColorablePoint();
Colorable3DPoint v = new Colorable3DPoint();
Colorable w = u;
w.setColor(Color.BLACK);
w = v;
w.setColor(Color.RED);
ColorablePoint method
setColor() is invoked.
Colorable3DPoint method
setColor() is invoked.
40
Class
Method
Variable
Abstract
Final
Static
None
Private
Public
Protected
41
Download