Interfaces (example provided by G.
Sheblι,
2004)
Example
|
Public interface Relation
{ |
|
// returns true if a >
b |
|
public boolean isGreater(
Object a, Object b ); |
|
|
|
//returns true if a <
b |
|
public boolean isLess(
Object a, Object b ); |
|
|
|
//returns true if a ==
b |
|
public boolean isEqual(
Object a, Object b ); |
|
} |
Implementation
|
Public class Line
implements Relation { |
|
//
variables |
|
private double x1; //x-
value |
|
private double x2; //x-
value |
|
private double y1; //y-
value |
|
private double y2; //y-
value |
|
|
|
//
Constructor |
|
public Line ( double x1,
double y1, double x2, double, y2) { |
|
this.x1 = x1; |
|
this.x2 = x2; |
|
this.y1 = y1; |
|
this.y2 = y2; |
|
} |
|
// Calculate
length |
|
public double length( )
{ |
|
return
Math.sqrt( (x2-x1) * ( x2-x1) + (y2-y1) * (y2-y1)
); |
|
} |
|
// returns true if a >
b |
|
public boolean isGreater(
Object a, Object b ); |
|
return
((Line)a).length() > ((Line)b).length(); |
|
} |
|
//returns true if a <
b |
|
public boolean isLess(
Object a, Object b ); |
|
return
((Line)a).length() < ((Line)b).length(); |
|
} |
|
//returns true if a ==
b |
|
public boolean isEqual(
Object a, Object b ); |
|
return
((Line)a).length() == ((Line)b).length(); |
|
} |
|
//
toString |
|
public String toString (
) { |
|
String
s; |
|
s = Line from
( + x1 + , + y1 + ) to ( |
|
+ x2 + , + y2 + ): Length = +
length(); |
|
return
s; |
|
} |
|
} |
Test
driver
|
public class TestLine
{ |
|
//
main |
|
public static void
main(String[] args) { |
|
|
|
// Create
Objects |
|
o[0] = new
Line(0,0,2,1); |
|
o[1] = new
Line(0,0,1,-1); |
|
o[2] = new
Line(-1,1,1,1); |
|
o[3] = new
Line(2,0,0,0); |
|
o[4] = new
Line(0,2,-2,0); |
|
|
|
// Sorte
objects |
|
SortObj.sort(o); |
|
|
|
//Show
results |
|
for ( int i = 0; i <
o.length; i++) { |
|
System.out.println(o[i].toString()); |
|
} |
|
} |
|
} |
Method to sort objects that
implement interface Relation into ascending order
|
// Define sort
method |
|
public class SortObj
{ |
|
|
|
// Declare
variables |
|
int i,j;
//indices |
|
int iptr; // pointer to
smallest |
|
Object
temp; //temp variable
for swapping |
|
//Sort
values |
|
for ( i = 0; i <
o.length; i++ ) { |
|
//Find minimum
value |
|
iptr =
i; |
|
for ( j =
i + 1; j < o.length; j++ |
|
if ( ( (Relation)o[0]).isLess( |
|
(Relation) o[j], (Relation) o[iptr] )) |
|
iptr = j; |
|
} |
|
// iptr now points to the
min value, so swap |
|
if ( i != iptr )
{ |
|
o[i] = o[iptr]; |
|
o[iptr] = temp; |
|
} |
|
} |
|
//Return sorted
objects |
|
return
o; |
|
} |
|
} |