Lec05 Slides
Lec05 Slides
Lecture 5
Testing (cont.)
Interfaces, subtyping,
polymorphism
A2 will be released soon
A. 0 void increment() {
if (counts == 9999) {
B. 1 counts = 0;
C. 2 }
else {
D. 9,999
counts += 1;
E. 10,000 }
}
Interfaces
“Interfaces”
• Mechanism by which two parties work together, decided ahead of
time
• HDMI cable: interface between laptop and projector
• ¼”-20 screw: interface between tripods and camera gear
• API: interface between client programmers and classes
• Parties don’t need to know each other’s details
4.
Java interfaces
• Guarantee to clients what a type /** Closed interval on real
* number line. */
can do, without committing to
details (i.e. fields) public interface Interval {
• Method signatures /** Left endpoint. */
• Method return types double left();
• Method specs /** Right endpoint. */
• Method declarations are double right();
implicitly public /** Whether x is contained
* in interval. */
double contains(double x);
}
Client A code
static boolean intervalsOverlap(Interval i1,
Interval i2) {
return i1.left() <= i2.right() &&
i2.left() <= i1.right();
}
Implementer’s code
Option A Option B
public class TwoPtInterval public class
implements Interval { CenterInterval
/** Left endpoint. */ implements Interval {
private double left; /** Midpoint. */
/** Right endpoint. */ private double center;
private double right; /** Width. */
private double width;
// ...
// ...
}
}
Client B code
TwoPointInterval tpi = new TwoPtInterval(-2, 3);
CenterInterval ci = new CenterInterval(4, 2);
// Is this allowed?
boolean overlap = intervalsOverlap(tpi, ci);
Object diagram
TwoPointInterval
intervalsOverlap()
left: double -2.0
• Static type: types declared for variables & return values, derived for
expressions (compile-time)
• Dynamic type: the type of an object being referenced (runtime)
A. Yes
B. No
C. Only if they know more than the compiler
Compile-time reference rule
• Client can only request behavior supported by the static type
• It is possible to ask about the dynamic type of an object and cast the
reference so that additional behavior is available, but this is usually
not good OOP practice
• instanceof
• Example next time: equals()