1School of Information Technologies / The University of Sydney 2011-S2
Software Development in Java
Week11 • Semester 2• 2015
Interfaces & Polymorphism
Practical Homework 3: in Lab, tonight
Assignment Submission: 6:00pm, Wed. 21 Oct
Assignment Demo: Tutorial, Wed. 21 Oct
School of Information Technologies / The University of Sydney 2011-S2
Review on Inheritance
2School of Information Technologies / The University of Sydney 2011-S2
Inheritance
Inheritance allows a software developer to derive a new class
from an existing one
The existing class is called the parent class, or superclass, or
base class
The derived class is called the child class or subclass
As the name implies, the child inherits characteristics of the
parent. That is, the child class inherits the methods and data
defined by the parent class
School of Information Technologies / The University of Sydney 2011-S2
Inheritance
We can write code in the superclass, and reuse it in the subclasses
without repeating it again
Java keyword extends
A class can only directly extend one parent
It implicitly extends Object if nothing else is declared.
The subclass inherits fields and methods of the parent
Plus whatever is defined in the subclass itself
Proper inheritance creates an is-a relationship,
meaning the child is a more specific version of
the parent
Person
Student
is
-a
3School of Information Technologies / The University of Sydney 2011-S2
Abstract Class
abstract method: no method body, e.g.:
public abstract void draw( );
abstract class: a class that has an abstract method
the subclasses provide implementation of an abstract
method
NO object can be created from an abstract class.
Abstract classes enforce code reuse and software design.
School of Information Technologies / The University of Sydney 2011-S2
An Example: 2D shapes
We are going to define 2D shapes such
as circles, rectangles and triangles
4School of Information Technologies / The University of Sydney 2011-S2
Rectangle class (version 1)
public class Rectangle {
private double x; // x coordinate of bottom left hand corner
private double y; // y coordinate of bottom left hand corner
private double h; // height
private double w; // width
public double getX(){ ...
public double getY(){ ...
public double getWidth(){ ...
public double getHeight(){ ...
public Rectangle(double a, double b, double c, double d){
x=a; y=b; h=c; w=d;
}
public double area (){
return w*h;
}
public double perimeter (){
return 2*(w+h);
}
}
(x,y)
h
w
.
School of Information Technologies / The University of Sydney 2011-S2
Circle class (version 1)
public class Circle {
private double x; // (x,y) is the center of the circle
private double y;
private double r; // radius
public double getX(){ ...
public double getY(){ ...
public double getRadius(){ ...
public Circle(double a, double b, double c){
x=a; y=b; r=c;
}
public double area (){
return r*r*Math.PI;
}
public double perimeter (){
return 2*r*Math.PI;
}
}
(x,y)r
5School of Information Technologies / The University of Sydney 2011-S2
Triangle class (version 1)
public class Triangle {
private double x; // x0
private double y; // y0; the points
private double x1; // (x0,y0),(x1,y1),(x2,y2)
private double y1; // are the
private double x2; // vertices of
private double y2; // the triangle
public double getX(){...
public double getY(){...
public double getX1(){...
public double getY1(){...
public double getX2(){...
public double getY2(){...
public Triangle(double a, double b, double c, double d, double e, double f){
x0=a;y0=b;x1=c;y1=d;x2=e;y2=f;
}
public double area (){
double a = Math.sqrt(((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1)));
double b = Math.sqrt(((x0-x2)*(x0-x2) + (y0-y2)*(y0-y2)));
double c = Math.sqrt(((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
double s = 0.5*(a+b+c);
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public double perimeter (){ ...
(x0,y0)
(x1,y1)
(x2,y2)
School of Information Technologies / The University of Sydney 2011-S2
Rectangles, circles, and
triangles are all shapes.
Rectangles, circles, and
triangles all have
A location (x,y)
An area
A perimeter
Specifically, in addition:
Rectangles have a
height and a width
Circles have a
radius
Triangles have two
other vertices.
(x,y)
(x,y)
(x,y)
We can create a
superclass to
generalise
rectangles, circles,
and triangles.
Use the concept of inheritance
6School of Information Technologies / The University of Sydney 2011-S2
Use the concept of inheritance
We can define a superclass to generalize the shapes
Practice on implementation by yourself!
School of Information Technologies / The University of Sydney 2011-S2
Java Interfaces
7School of Information Technologies / The University of Sydney 2011-S2
Interfaces
A java interface is not a class.
An interface defines a type to generalize the common functions of similar
classes
An interface has a well defined API to list its functions by only specifying their
names, inputs and outputs and types, while without concrete implementation.
An interface includes a list of method signatures (name, parameters) and
return type, but without method bodies
interface InterfaceName {
method signatures // but without any implementation
}
interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
There are many classes of bicycles.
Internally, they have different
methods of changing gears and
applying brakes.
But from the outside point of view,
they have similar behaviour.
Syntax of interfaces:
School of Information Technologies / The University of Sydney 2011-S2
Implementing an Interface Type
Use implements keyword to indicate that a class implements an
interface type
A class can implement more than one interface;
then the class must provide the method implementations for
all the methods defined by all the interfaces that it
implements
public class ClassName implements InterfaceName1, InterfaceName2, ...
{
// methods (need to be declared as public)
// fields
}
8School of Information Technologies / The University of Sydney 2011-S2
interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Java Interfaces
Include a list of method signatures (name, parameters) and return type
but without method body
An interface can be implemented by a class. The class supplies method
bodies for all the methods defined in the interface.
class GrannyBike implements Bicycle{
…
public void applyBrakes(int decrement) {
backPedal ();
}
. . … …
class Racer implements Bicycle{
…
public void applyBrakes(int decrement) {
squeezeLever();
}
. . … …
im
plem
entation
School of Information Technologies / The University of Sydney 2011-S2
interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Java Interfaces
No constructors
Can be used to declare a reference variable
But cannot be used to construct an object; and the object must
constructed from a class that implements the interface
class GrannyBike implements Bicycle{
…
public void applyBrakes(int decrement){
backPedal ();
}
. . … …
class Racer implements Bicycle{
…
public void applyBrakes(int decrement){
squeezeLever();
}
. . … …
…
Bicycle b;
if (userAge>70) b = new GrannyBike();
else b = new Racer();
…
//client class
C
onstruct from
a class that
im
plem
ented
the interface
9School of Information Technologies / The University of Sydney 2011-S2
2D Shapes Revisit
School of Information Technologies / The University of Sydney 2011-S2
Interfaces
Rectangles, circles, and
triangles are all shapes.
Rectangles, circles, and
triangles all have
Getters for a given
vertex (x,y)
An area
A perimeter
Also:
Rectangles have a
height and a width
Circles have a
radius
Triangles have two
other vertices.
(x,y)
(x,y)
(x,y)
We can create an
interface called
Shape to generalise
the functions of
rectangles, circles,
and triangles.
10
School of Information Technologies / The University of Sydney 2011-S2
Interfaces
Note:interface Shape has
some getters for instance variables, common to Rectangle,
Circle, and Triangle
some method signatures common to the classes Rectangle,
Circle, and Triangle (methods area(), perimeter()), but no
method bodies
No constructors
public interface Shape {
double getX(); // getter: x coordinate of location
double getY(); // getter: y coordinate of location
double area ();
double perimeter ();
}
Java interface gives a way of defining a generalization of the classes
Rectangle, Circle, and Triangle
School of Information Technologies / The University of Sydney 2011-S2
Rectangle, Circle, and Triangle classes (version 2)
public class Circle implements Shape {
...
public double getX(){ //method body...
public double getY(){//method body...
...
public double area (){//method body...
public double perimeter (){//method body...
public class Triangle implements Shape {
...
public double getX(){//method body...
public double getY(){//method body...
...
public double area (){//method body ...
public double perimeter (){//method body...
public class Rectangle implements Shape
{
...
public double getX(){//method body...
public double getY(){//method body...
...
public double area (){//method body ...
public double perimeter (){//method body ...
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
implements
(indicating these classes
Must provide method
implementations
for all the interface methods)
11
School of Information Technologies / The University of Sydney 2011-S2
Circle class (version 2)
public class Circle implements Shape {
private double x; // the center of
private double y; // the circle is at (x,y)
...
public double getY(){ ...
public double getRadius(){....
.....
public double area (){
return r*r*Math.PI;
}
public double perimeter (){
return 2*r*Math.PI;
}
...
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
implements
School of Information Technologies / The University of Sydney 2011-S2
Rectangle class (version 2)
public class Rectangle implements Shape {
private double x; // x coordinate
private double y; // y coordinate
...
public double getY(){ ...
public Rectangle(double a, double b,
double c, double d){ ..
...
public double area (){
return w*h;
}
public double perimeter (){
return 2*(w+h);
}
...
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
implements
12
School of Information Technologies / The University of Sydney 2011-S2
Triangle class (version 2)
public class Triangle implements Shape {
private double x0;
private double y0;
...
public double getX(){ ...
public double getY(){ ...
...
public double getY2(){
...
public Triangle(double a, …
…
public double area (){
double a = Math.sqrt(((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1)));
double b = Math.sqrt(((x0-x2)*(x0-x2) + (y0-y2)*(y0-y2)));
double c = Math.sqrt(((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
double s = 0.5*(a+b+c);
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public double perimeter (){
double a = Math.sqrt(((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1)));
double b = Math.sqrt(((x0-x2)*(x0-x2) + (y0-y2)*(y0-y2)));
double c = Math.sqrt(((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
return a+b+c;
}
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
implements
When multiple classes
implement the same
interface, each class
implements the
methods of the interface
in different ways
School of Information Technologies / The University of Sydney 2011-S2
Interfaces
Notes
An interface defines the interface
of a set of classes, i.e. what to do,
but it does not define how the
classes work.
Methods defined in an interface
are automatically public.
Corresponding methods in
classes that implement the
interface must be public
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
public class Rectangle
implements Shape {
...
private double h; // height
...
public double area (){
return w*h;
}
...
13
School of Information Technologies / The University of Sydney 2011-S2
Interfaces
Notes
Every Rectangle object is a specific
Shape, and thus has all the functions
of Shape
Thereby Rectangles must have
public methods
getX(), with no parameters
getY(), with no parameters
area(), with no parameters
perimeter(), with no parameters
Rectangles may have instance
variables and more public methods,
but (since Rectangle implements
Shape), they must have those
methods specified in the interface
Shape.
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
public class Rectangle implements
Shape {
...
private double h; // height
...
public double area (){
return w*h;
}
...
School of Information Technologies / The University of Sydney 2011-S2
Circle class (version 3) with a toString method
public class Circle implements Shape {
private double x; // the center of
private double y; // the circle is at (x,y)
private double r; // radius
public double getX(){ ...
public double getY(){ ...
public double getRadius(){ ...
public Circle(double a, double b, double c){
x=a; y=b; r=c;
}
public double area (){ ...
public double perimeter (){ ...
public String toString(){
return "Circle center (" + x + "," + y + ") with radius " + r;
}
toString() : a method that
represents an object by a string
Example: If an object c of type Circle has x=3.1, y=1.6, r=4.7,
then c.toString() returns "Circle center (3.1,1.6) with radiu r=4.7”
Similarly, toString methods
can be added to the
Triangle and Rectangle
classes
14
School of Information Technologies / The University of Sydney 2011-S2
Rectangle class (version 3) with a toString method
public class Rectangle implements Shape {
...
...
public String toString(){
return "Rectangle bottom L corner at (" + x + "," + y +
") with height " + h + " and width " + w;
}
....
Example:
If an object rect of type Rectangle has x=5.4, y=7.3, h=6.1, and w=1.2, then
rect.toString() returns
“Rectangle bottom L corner at (5.4,7.3) with height 6.1 and width 1.2”
School of Information Technologies / The University of Sydney 2011-S2
A simple test class for interface Shape
public class ShapeTester {
public static void main(String[] args) {
Shape s;
s = new Rectangle(100, 100, 100, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Circle(100, 100, 100);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Triangle(100, 100, 100, 200, 200, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
}
}
Variable s has type Shape
s refers to an new object
of type Rectangle
s refers to an new object
of type Circle
s refers to an new
object of type
Triangle
15
School of Information Technologies / The University of Sydney 2011-S2
A simple test class for interface Shape
public class ShapeTester {
public static void main(String[] args) {
Shape s;
s = new Rectangle(100, 100, 100, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Circle(100, 100, 100);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Triangle(100, 100, 100, 200, 200, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
}
}
Using the toString
method defined for
each of the classes
Rectangle, Circle, and
Triangle
School of Information Technologies / The University of Sydney 2011-S2
public class ShapeTester {
public static void main(String[] args) {
Shape s;
s = new Rectangle(100, 100, 100, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Circle(100, 100, 100);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
...
}
Rectangle bottom L corner at (100.0,100.0) with height 100.0 and width 200.0
area=20000.0 perimeter=600.0
---------
Circle center (100.0,100.0) with radius 100.0 area=31415.926535897932
perimeter=628.3185307179587
---------
...
16
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism via Interfaces
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism via Interfaces
An interface name can be used as the type of a reference variable.
An interface reference variable can be used to refer to any
object of any class that implements the interface.
Polymorphism (many shapes): Behaviors can vary depending
on the actual type (dynamic type) of an object, i.e., the actual
type of the object determines the method implementation to be
performed
17
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism via Interfaces
public class ShapeTester {
public static void main(String[] args) {
Shape s;
s = new Rectangle(100, 100, 100, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Circle(100, 100, 100);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
System.out.println("---------");
s = new Triangle(100, 100, 100, 200, 200, 200);
System.out.print(s);
System.out.println(" area=" + s.area() + " perimeter=" + s.perimeter());
}
}
Variable s has type Shape
s refers to an new object
of type Rectangle
s refers to an new
object of type Circle
s refers to an
new object of
type Triangle
The same reference
variable (s) can refer
to different objects at
different time. And
hence, different
methods (toString)
are invoked
correspondingly.
An interface reference variable can be used to refer to any object of
any class that implements that interface.
The program varies according to the class that is plugged in– this
phenomenon is called polymorphism
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism via Interfaces
Note:
When we use an interface reference variable, we can invoke only the
methods defined in the interface; otherwise, we will have a compiler
error.
public class Circle implements Shape {
private double x; // the center of
private double y; // the circle is at (x,y)
...
public double getY(){ ...
public double getRadius(){....
.....
public double area (){
return r*r*Math.PI;
}
public double perimeter (){
return 2*r*Math.PI;
}
...
public interface Shape {
double getX(); // x coordinate
double getY(); // y coordinate
double area ();
double perimeter ();
}
Shape sh;
sh = new Circle(100,100,100);
sh.getRadius(); //wrong!
Compiler error: the method
getRadius() is undefined for the
type Shape
18
School of Information Technologies / The University of Sydney 2011-S2
Going a bit further:
A collection of shapes is a scene
School of Information Technologies / The University of Sydney 2011-S2
Going a bit further:
A collection of shapes is a scene
We know how to make a collection . . ... ...
19
School of Information Technologies / The University of Sydney 2011-S2
Scene class: instance fields, constructors, getters, and
some private methods
import java.util.ArrayList; ...
public class Scene {
private ArrayList shapeList;
public Scene(){
shapeList = new ArrayList();
}
public Scene(String fileName){
shapeList = new ArrayList();
readScene(fileName);
}
public ArrayList getShapeList() {
return shapeList;
}
private void addShape (Shape s ) {
shapeList.add(s);
}
private void readScene(String fileName){ ...
....
....
getter
Two
constructors
Instance field
Adds a shape to the scene
Reads the scene from a file
School of Information Technologies / The University of Sydney 2011-S2
Scene class: instance fields, constructors, getters, and
some private methods
import java.util.ArrayList; ...
public class Scene {
private ArrayList shapeList;
public Scene(){
shapeList = new ArrayList();
}
public Scene(String fileName){
shapeList = new ArrayList();
readScene(fileName);
}
public ArrayList getShapeList() {
return shapeList;
}
private void addShape (Shape s ) {
shapeList.add(s);
}
private void readScene(String fileName){ ...
....
....
An interface name can be
used as the type of a
method parameter.
In such a case, any object
of any class that
implements the interface
can be passed into the
method.
20
School of Information Technologies / The University of Sydney 2011-S2
Scene class:
private method to
read a scene from
a file
public class Scene {
...
private void readScene(String fileName){
try{
File file = new File(fileName);
Scanner fileReader = new Scanner(file);
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
Scanner lineReader = new Scanner(line);
String command = new String(lineReader.next());
if (command.equals("triangle")){
double x0 = lineReader.nextDouble();
...
addShape(new Triangle(x0,y0,x1,y1,x2,y2));
}
else if (command.equals("rectangle")){
...
addShape(new Rectangle(x,y,h,w));
}
else if (command.equals("circle")){
addShape(new Circle(x,y,r));
}
else System.out.println("Unknown shape: skipping");
}
} ...
An interface name can be
used as the type of a method
parameter.
In such a case, any object of
any class that implements
the interface can be passed
into the method.
School of Information Technologies / The University of Sydney 2011-S2
Scene class: how to draw a scene
import javax.swing.*;
public class Scene { ...
...
public void draw(){
for (Shape s: shapeList) {
s.draw();
}
}
...
import javax.swing
21
School of Information Technologies / The University of Sydney 2011-S2
Testing the Scene class
public class SceneTester {
public static void main(String[] args) {
Scene s = new Scene("C:/temp/temp.txt");
s.draw();
for (Shape t: s.getShapeList()){
System.out.println(t);
}
}
}
Triangle with vertices at (0.0,0.0)-(100.0,100.0)-(100.0,200.0)
Triangle with vertices at (0.0,100.0)-(200.0,200.0)-(100.0,400.0)
Circle center (400.0,400.0) with radius 200.0
Circle center (100.0,300.0) with radius 560.0
Rectangle bottom L corner at (100.0,200.0) with height 500.0 and width 600.0
Rectangle bottom L corner at (200.0,300.0) with height 400.0 and width 500.0
triangle 0 0 100 100 100 200
triangle 0 100 200 200 100 400
circle 400 400 200
circle 100 300 560
rectangle 100 200 500 600
rectangle 200 300 400 500
Input file C:/temp/temp.txt
O
ut
pu
t
Output
School of Information Technologies / The University of Sydney 2011-S2
Abstract Class versus Interface
They are both used to enforce code reuse and class design.
Abstract class can have concrete methods but interface does not.
A class
extends only one abstract class
implements many interfaces.
A class declared as abstract does not have to contain abstract
methods -- simply declaring the class as abstract.
An interface type does not have instance fields, but can have
static fields.
22
School of Information Technologies / The University of Sydney 2011-S2
Interface Hierarchies
Inheritance can be applied to
interfaces as well as classes
That is, one interface can be
derived from another interface (by
extends)
The child interface inherits all
abstract methods of the parent
A class implementing the child
interface must define all methods
from both the ancestor(s) and
child interfaces
extends
implements