1 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The...
-
Upload
linette-hancock -
Category
Documents
-
view
213 -
download
0
Transcript of 1 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The...
1
Lecture 07 Interfaces and related issues
Reading for these lectures: Weiss, Section 4.4 (The interface), p. 110.ProgramLive, Section 12.1
In User Interface there are personal preferences, but there are rules (guidelines) about what is right or wrong. …
Apple and Xerox basically modeled most of their controls after things that we are familiar with in the real world; then they made behaviors consistent to increase predictability. Radio-Buttons, Checkboxes, Sliders are all things that people have seen before. …Later, others (like NeXT, or some Unix folks) added controls (like tabs), they modeled them after things in the real world (like little tabs on folders, file drawers or in notebooks). Again, that interface was clear and intuitive.
Microsoft has contributed one control to the interface world: the Combo-Box. And like almost all things Microsoft, it is a bad implementation of user interface.
David Every, http://igeek.com/articles/Interface/ComboBox.txt
2
Interfaces and related issues
[Note: next Thursday, a review of classes/ subclasses, etc. 80 people for, 15 against.]
no multiple inheritance with classes
public class Student { public class Employee {… …} }
public class StudentEmployeeextends Student, Employee { … }
Multiple inheritance has been tried in several languages, but it never works correctly. Trouble with ambiguity. E.g. what if method getName is defined in both superclasses but they yield different values? No good theory of such multiple inheritance has been developed yet, so Java does not allow it.
not allowed.doesn’t work.
3
An interface contains the result types (or void) and signatures of some methods. The methods are called “abstract” because their bodies are not present; the bodies are replaced by semi-colons. The methods are automatically public.
public interface Comparable {/** = if this Object < ob then a negative integer
if this Object = ob, then 0 if this Object > ob, then a positive integer */
int compareTo (Object ob);}
The signature of a method consists of its name and its parameter declarations (enclosed in parentheses and separated by commas).
The interface
abstract method: body replaced by “;”
no prefix (static, public, etc.)
4
Abstract data type
Type: a bunch of values together with operations on them.
We can write an interface that DEFINES such a type. We call it an “abstract data type” because we don’t give a concrete implementation of it, we just define it “abstractly”
5
Type List211
/** A list is a sequence of Objects. */public interface List211 {
/** Make the list empty */ void makeEmpty();
/** Add item e to the list */ void add(Object e);
/** Delete an item from the list */ void delete();
/** = an item in the list */ Object getItem();
/** = the number of items in the list */ int size();}
Operations are not only abstract but ambiguous. Doesn’t say which item to delete or where to add an item.
6
Implement list as a stack
/** An instance is a stack s of Objects */public class Stack1 implements List211 {
…
}
Because of the implements clause, class Stack1 MUST define all the methods that appear in interface List211. It is a syntactic error if class Stack1 does not define them.
implements clause
7
Implement list as a stack
/** An instance is a stack s of Objects */public class Stack1 implements List211 { /** Make the stack empty */ public void makeEmpty() { }
/** add item e to the front of the stack */ public void add(Object e) { }
/** delete item from the front of the stack */ public void delete() { }
/** = the front item of the stack */ public Object getItem() { return null; }
/** = the number of items in the stack */ public int size() { return 0; }}
Specs made more specific. Bodies not written yet.
8
Class invariant: describes the fields and the values they contain:
/** An instance is a stack s of Objects, with a maximum size */public class Stack1 implements List211 { /** Stack s appears in b[0..n-1], so that s contains n items. b[0] is the bottom and b[n-1] the top of the stack*/ public Object[] b; public int n;
/** Constructor: empty stack of <= m items */ public Stack1(int m) { b= new Object[m]; n= 0; }
…
We turn to DrJava to look at this class in detail. The class will be available on the web.
9
public interface Comparable {/** = if this Object < ob then a negative integer
if this Object = ob, then 0 if this Object > ob, then a positive integer */
int compareTo (Object ob);}
It has ONE method, compareTo.
Interface Comparable
10
public class Shape implements Comparable {…// = if this Object < ob then a negative integer
// if this Object = ob, then 0// if this Object > ob, then a positive integer// (it’s expected that ob is really a Shape)
int compareTo(Object ob) {if (this.area() < ((Shape)ob).area())
return -1;if (this.area() == ((Shape)ob).area())
return 0;return 1;
}}
(in this case, Shapes are ordered by their area)
Implementing method compareTo
In this case, the parameter of compareTois expected to be an instance of Shape, because the method is defined in Shape
ob is castto Shape
11
public class ArrayMethods {// = index of the max value in nonempty bpublic static int max(Comparable[] b) {
int j= 0;// {invariant: b[j] is the max of b[0..i-1]}for (int i= 1; i != b.length; i= i+1) {
if (b[i].compareTo(b[j]) > 0)j= i;
}return j;
}}
Shape[] s= new Shape[20];Integer[] x= new Integer[100];
Fill s and x with values.int maxs= ArrayMethods.max(s);int maxx= ArrayMethods.max(x);
Why is the interface concept useful?
max will find the max of any array b whose base class implements Comparable!
12
public class ArrayMethods {// = index of the max value in nonempty bpublic static int max(Comparable[] b) {
int j= 0;// {invariant: b[j] is the max of b[0..i-1]}for (int i= 1; i != b.length; i= i+1) {
if (b[i].compareTo(b[j]) > 0)j= i;
}return j;
}}
Shape[] s= new Shape[20];Fill s with values.int maxs= ArrayMethods.max((Comparable[]) s);int maxs= ArrayMethods.max(s);
An interface acts like a type, and casts to and from an interface are allowed!
unnecessary cast because it widens
13
public class Shape implements Comparable{ … }
public class Parallelogram extends Shapeimplements Comparable, Comp2{ … }
public interface Comparable { … }
public interface In1 { … }
public interface Comp2 extends In1 {… }
Class and interface hierarchies
Object
Shape
Parallelogram
An interface, like aclass, is handled likea type: can cast to andfrom an interface.
14
public class Shape implements Comparable{ … }
public class Parallelogram extends Shapeimplements Comparable, Comp2{ … }
public interface Comparable { … }public interface In1 { … }public interface Comp2 extends In1 {… }
Class and interface hierarchies
Object
Shape
Parallelogram
Comparable
Comparable
Comp2
In1
Upward cast: widening;done automaticallywhen necessary
Downward cast: narrowing; notautomatic
15
Parallelogram p= new Parallelogram(); legalShape s= (Shape) p; legal (Comparable) p legal
(Comparable) s legal (Comp2) p legal (Comp2) s illegal
(In1) p legal(In1) s illegal((In1)p).equals(…) legal
In1 I= (In1) p; Using In1, can reference only names accessible in In1.
Class and interface hierarchies Object
Shape
Parallelogram
Comparable
Comparable Comp2
In1
Note that Objectacts like a superinterface
Object ObjectObject
16
public class Arrays {public static int max(Comparable[] b) {
int j= 0;// {invariant: b[j] is the max of b[0..i-1]}for (int i= 1; i != b.length; i= i+1) {
if (b[i].compareTo(b[j]) > 0)j= i;
}return j;
}}public class Shape implements Comparable {
int compareTo(Object ob) {Shape x= (Shape)ob;if (this.area() < x.area()) return -1;if (this.area() == x.area()) return 0;return 1;
}}public class M {
public static void main(…) {Shape[] s= new Shape[20];Fill s with values.int m= Arrays.max(s); L1:
}}
**
17
main
pars
M
in systemm
s a0
0 1
19
a0a1a2…
a20Shape[]
Arrays
L1
max
b a0 Comparable[]
j 0 i 1
a1
ShapeareacompareTo
a2
ShapeareacompareTo
Shape a2
**
ob a1 Object[]
x a1 Shape []
This slide shows the call stack for the call
Arrays.max(s);
on the previous slide, just after execution of
Shape x= (Shape)ob;
in method a2.compareTo.
18
Functors (function objects)
Interface Comparable doesn’t fit all situations. For an array of integers, there are several ways to sort it --ascending order, descending order, in order of distance from 0 (e.g. 0,1,-1, 2, -2, 3, -4, …), etc. We want to use the same sort method to sort the array in any order.
Solution: pass a comparison function to method sort:
// Sort array b using sort method fpublic static void sort(int[] b, function f) {
… if f(b[i],b[j]) ...}
public static void main(String[] pars) {int[] x= new int[50]; Fill array x with values;sort(x, greaterequal);sort(x, lessequal);
}
// = “x <= y”public static boolean lessequal(int x, int y)
{return x <= y;}
// = “x >= y”public static boolean greaterequal(int x, int y)
{return x >= y;}
illegal in Java!
19
Functors (function objects)
A function cannot be an argument, but an instance of a class that is guaranteed to contain a function can!
// A functor with boolean function compare(x,y)public interface CompareInterface {
// = x <= yboolean compare(Object x, Object y);
}
// Sort array b using functor cpublic static void sort(int[] b, CompareInterface c) {
… if c.compare(b[i],b[j]) ...}
An instance of interface is a functor: an instance with exactly one function defined it it.
parameter c is guaranteedto contain function compare
20
Consequence of using a functor
One sort method can be used to sort an array of any base class; you provide the functor that does the comparing.
// A functor with boolean function compare(x,y)public interface CompareInterface {
// = x compared to yboolean compare(Object x, Object y);
}
public class Less implements CompareInterface {// = “x < y”public boolean compare(Object x, Object y)
{return ((Integer )x).intValue() < ((Integer )y).intValue();}
}
public class Greater implements CompareInterface {// = “x > y”public boolean compare(Object x, Object y)
{return ((Integer )x).intValue() > ((Integer )y).intValue();}}
// Sort array b using functor cpublic static void sort(int[] b, CompareInterface c) {
… if c.compare(b[i],b[j]) ...}
21
Consequence of using a functor
// A functor with boolean function compare(x,y)public interface CompareInterface {
// = x compared to yboolean compare(Object x, Object y);
}
public class Less implements CompareInterface {// = “x < y”public boolean compare(Object x, Object y)
{return …; }}
public class Greater implements CompareInterface {// = “x > y”public boolean compare(Object x, Object y)
{return …; }}
// Sort array b using functor cpublic static void sort(int[] b, CompareInterface c) {
… if c.compare(b[i],b[j]) ...}
public static void main(String[] pars) {int[] x= new int[50]; Fill array x with values;sort(x, new Less());sort(x, new Greater());
}