Interface - Department of Computing Science

Download Report

Transcript Interface - Department of Computing Science

Revised 12/16/99
Data Abstraction - Interfaces
and Implementations
Cmput 115 - Lecture 1
Department of Computing Science
University of Alberta
©Duane Szafron 1999
Some code in this lecture is based on code from the book:
Java Structures by Duane A. Bailey or the companion structure package
About This Lecture

In this lecture we will learn how Java
objects and classes can be used to build
abstract data types.
©Duane Szafron 1999
2
Outline

Object Concepts

Interface

Use

Implementation

Java interfaces
©Duane Szafron 1999
3
What is an Object?
• some thing that has:
- identity
- state
- set of defined behaviours
* operations (methods) the object does
* requests operations (methods) other objects do
Example Object:
student (061342, Mary Doe, 1st year, Computing Science,
12 Bellvue Towers, [email protected], takes CMPUT
115, swims, gets a computer account)
©Duane Szafron 1999
4
What is a Class?
• a set of things that share (have in common):
- an identification technique
- state variables
- set of defined behaviours
* operations (methods) the object does
* requests operations (methods) other objects do
Example Class:
student class (student id, name, year, program, address,
email*, takes courses, activities*, special needs*)
©Duane Szafron 1999
5
Abstraction/Generalization/Specialization
student’ class (student id, name, year, program, address,
takes courses)
cmput-student class is a subclass of student’(email, gets
a computer account)
phys-ed-student class is a subclass of student’(activities)
student’
isa
cmput-student
©Duane Szafron 1999
isa
phys-ed-student
6
Objects are everywhere!
©Duane Szafron 1999
7
Types of Objects

Objects in the “real world”

User interface objects - e.g., windows, mouse
drivers

System objects - e.g., server, clients, proxies

Persistent management objects - e.g., files,
databases, versions, configurations

User objects - e.g., user preferences
©Duane Szafron 1999
8
Example of Data Structure Object

Develop a computer game in which resources are either
shared or competed for between players. How do you
manage these resources?

A common way is to use a queue.

Properties of queue request is serviced from
the front of the queue,
new requests are placed
at the rear of the queue.
Implement a queue of
players wishing to make
their next move.

©Duane Szafron 1999
Queue player = new QueueList()
// create a queue of players
player.add(name)
// add a player to the queue
player-done = player.remove
//remove a player from the queue
9
Object Concepts
An object has a public interface and a private
state.
 The interface is the set of all resources the class
provides.
 Objects that share the same interface are
organized into a group called a class and each
object in the class is called an instance of the
class. (object = instance of a class)
 The state of an object differentiates it from other
objects in the same class.

©Duane Szafron 1999
10
Object Class, Interface and State
external request
private
state
private
public interface
private
state
state
public interface
public interface
class
©Duane Szafron 1999
11
Interface, Implementation & Use

There are three aspects for any class:
– Interface: a description of the resources that the
class provides.
– Implementation: the code that describes the
private state of instances and implements the
computational resources of the class.
– Use: code in a using class causes new instances of
the used class to be created and invokes
computations on these instances.
©Duane Szafron 1999
12
Interface

In Java, the interface of a class includes:
–
–
–
–
–
The name of the superclass
Public variable declarations
Constructor declarations
Message declarations
Static method declarations

Note that in Java, the term interface has a
specific meaning that is slightly different than
our generic use of the term interface.

We will discuss Java interfaces later.
©Duane Szafron 1999
13
Interface - Ratio Class -1
public class Ratio
{ /* an object for storing a fraction */
public Ratio(int top, int bottom)
/* pre: bottom != 0
post: constructs a ratio equivalent to top/bottom
Do*/not be concerned about the “pre:” and “post:”
notation. It will be explained in the next lecture.
public int getNumerator()
/* post: return the numerator of the fraction */
public int getDenominator()
/* post: return the denominator of the fraction */
©Duane Szafron 1999
code based on Bailey pg. 8
14
Interface - Ratio Class -2
public double value()
/* post: returns the real value equivalent to ratio */
public Ratio add(Ratio other)
/* pre: other is non-null
post: return new fraction - the sum of this and
other */
©Duane Szafron 1999
code based on Bailey pg. 9
15
Use

In Java, a class A can use another class B by:
– Creating instances of class B.
– Sending messages to instances of class B.
– Invoking static methods from class B.
– Using variables that are declared in class B.
– Using message arguments that are
declared to be of class B.
©Duane Szafron 1999
16
17
Use - Ratio Class
public static void main(String[] args) {
Ratio r = new Ratio(1,1);
// r == 1.0
r = new Ratio(1,2);
// r == 0.5
r.add(new Ratio(1,3));
// r still 0.5
r = r.add(new Ratio(1,4));
// r == 0.75
System.out.println(r.value()); // 0.75 printed
}
©Duane Szafron 1999
code based on Bailey pg. 9
Implementation

In Java, a class implementation includes:
– Constructor code
– Message code (instance methods)
– Static (class) method code
– Bindings for static variables
©Duane Szafron 1999
18
Implementation - Ratio Class -1
import structure.*;
public class Ratio {
/* an object for storing a fraction */
protected int numerator;
// numerator of ratio
protected int denominator; // denominator of ratio
public Ratio(int top, int bottom) {
/* pre: bottom != 0
post: constructs a ratio equivalent to top/bottom */
Assert.pre(bottom != 0, "Denominator must not be 0");
this.numerator = top;
this.denominator = bottom;
}
©Duane Szafron 1999
code based on Bailey pg. 8
19
Implementation - Ratio Class -2
public int getNumerator() {
/* post: return the numerator of the fraction */
return this.numerator;
}
public int getDenominator() {
/* post: return the denominator of the fraction */
return this.denominator;
}
©Duane Szafron 1999
code based on Bailey pg. 8
20
Implementation - Ratio Class -3
public double value() {
/* post: returns the real value equivalent to ratio */
return (double)this.numerator
/(double)this.denominator;
}
}
public Ratio add(Ratio other) {
/* pre: other is non-null
post: return new fraction - the sum of this and other */
Assert.pre(other != null, "Other must not be null");
return new Ratio(this.numerator*other.denominator+
this.denominator*other.numerator,
this.denominator*other.denominator);
}
©Duane Szafron 1999
code based on Bailey pg. 9
21
Java Interfaces

For many classes, the interface and the
implementation are in the same file.

However, Java has a specific feature called an
interface that can be used to separate the
interface of a class from its implementation.

This is not usually done!

A Java interface contains no code, only
message signatures.
©Duane Szafron 1999
22
Java Interface - PlanarPoint -1
public interface PlanarPoint
{
public double getX();
/* post: returns the x coordinate. */
public double getY();
/* post: returns the y coordinate. */
public double getR();
/* post: returns the distance from the origin. */
public double getTheta();
/* post: returns the angle in radians from the x axis. */
©Duane Szafron 1999
23
24
Graphical Interpretation
Y
(r, Q) (x,y)
R
q
©Duane Szafron 1999
X
Java Interface - PlanarPoint -2
public void transform(double dr, double dTheta);
/* pre: if dr >= 0 or |dr| < current r
post: changes the r and theta coordinates by adding
the given values to them. */
public void translate(double dx, double dy);
/* post: changes the x and y coordinates by adding the
given values to them. */
public PlanarPoint add(PlanarPoint aPoint);
/* pre: aPoint is non-null
post: return new PlanarPoint - the sum of this and other
*/
}
©Duane Szafron 1999
25
Implementing Java Interfaces

A Java class is used to implement a Java
interface.

The class must provide code for each
message in the Java interface.

The class name must be different from the
Java interface name.
©Duane Szafron 1999
26
Class - CartesianPoint -1
public class CartesianPoint implements PlanarPoint
{
protected double x; // x coordinate of point
protected double y; // y coordinate of point
public CartesianPoint(double x, double y) {
/* post: constructs a Point with the given coordinates */
this.x = x;
this.y = y;
PlanarPoint
}
CartesianPoint
©Duane Szafron 1999
PolarPoint
27
Class - CartesianPoint -2
public double getX() {
/* post: returns the x coordinate. */
return this.x;
}
public double getY() {
/* post: returns the y coordinate. */
return this.y;
}
©Duane Szafron 1999
28
Class - CartesianPoint -3
public double getR() {
/* post: returns the distance from the origin. */
return Math.sqrt((this.x*this.x) + (this.y*this.y));
}
©Duane Szafron 1999
29
Class - CartesianPoint -4
public double getTheta() {
/* post: returns the angle in radians from the x axis. */
double angle;
angle = Math.atan(this.y/this.x);
if (this.x < 0)
angle = angle + Math.PI;
return angle;
}
©Duane Szafron 1999
30
31
Graphical Interpretation
Y
Assume x < 0
q+p
q
R
(r, q+p)
(x,y)
©Duane Szafron 1999
q
X
Class - CartesianPoint -5
public void transform(double dr, double dTheta) {
/* pre: if dr < 0 then |dr| < current r
post: changes the r and theta coordinates by adding
the given values to them. */
double r; double theta;
Assert.pre((dr>=0)|| (Math.abs(dr) <= this.getR()),
”require that dr >= 0 or abs(dr) <= r");
r = this.getR() + dr;
theta = this.getTheta() + dTheta;
this.x = r * Math.cos(theta);
this.y = r * Math.sin(theta);
}
©Duane Szafron 1999
32
33
Graphical Interpretation
Y
(r1+r2, Q1+Q2)
Transform Method
(r1, Q1)
q2
q1
©Duane Szafron 1999
X
Class - CartesianPoint -6
public void translate(double dx, double dy) {
/* post: changes the x and y coordinates by adding the
given values to them. */
this.x = this.x + dx;
this.y = this.y + dy;
}
©Duane Szafron 1999
34
Class - CartesianPoint -7
public PlanarPoint add(PlanarPoint aPoint) {
/* pre: other is non-null
post: return new PlanarPoint - the sum of this and
other */
}
}
Assert.pre(other != null, "Other must not be null");
return new CartesianPoint(this.x + aPoint.getX(),
this.y + aPoint.getY());
/* Note that we cannot use aPoint.x or aPoint.y since aPoint
might not be a Cartesian Point. It may be an instance of some
other class that implements the PlanarPoint interface. */
©Duane Szafron 1999
35
Multiple Classes can Implement a
Java Interface

We can have an arbitrary number of classes
that implement the same interface.

For example, we could have another class
that implements the PlanarPoint interface,
named the PolarPoint class (see the web for
code).

We can declare variables to be the Interface
type, but must create instances of the
implementation classes to bind them to.
©Duane Szafron 1999
36
Using PlanarPoint
Y
37
(r(3+3,
+r
,
Q
+
Q
1
2)
1 2 4+4)
q2
(r1, Q1)
(3.0,4.0)
q1
public void main(String args[]) {
PlanarPoint cartPoint, polarPoint, sumPoint;
cartPoint = new CartesianPoint(3.0, 4.0);
polarPoint = new PolarPoint(5.0, Math.atan(4.0 / 3.0));
sumPoint = cartPoint.add(polarPoint);
System.out.println(sumPoint); /*(6.0, 8.0) */
sumPoint = polarPoint.add(cartPoint);
System.out.println(sumPoint); /* <10.0, 0.927>*/
}
©Duane Szafron 1999
X
Some Principles from the Textbook
1. The principled programmer understands a
principle well enough to form an opinion
about it.
2. Free the future: reuse code.
3. Design and abide by the interfaces as though
you were the user.
4. Declare the data fields protected-- that way
you cannot access them from outside the
class and you are forced to access through
the interface.
©Duane Szafron 1999
principles from Bailey ch. 1
38