Take a look on codepublic class Cons extends ALoBooks { private Book first; private ALoBooks rest; public ConsBook first, ALoBooks rest { this.first = first; this.rest = rest; } //Class
Trang 1Chapter 06 – part VI
Abtraction with interfaces
Trang 2Abstracting over data definitions with object
Trang 3A Author contains:
- name - dayOfBirth
Many of the class hierarchies we have seen look alike
Trang 4• Many methods for these classes look alike as well and in
some cases are completely identical
– For example, the code for counting the number of items in a list looks the same for all kinds of lists
– The methods to determine whether a list contains some item is similar for all lists
• Repeating the same code is a major source of errors in
Trang 5Take a look on code
public class Cons extends ALoBooks {
private Book first;
private ALoBooks rest;
public Cons(Book first, ALoBooks rest) {
this.first = first;
this.rest = rest;
}
//Class ALoAuthors public abstract class ALoAuthors { }
//Class Empty public class Empty extends ALoAuthors { }
//Class Cons public class Cons extends ALoAuthors { private Author first;
private ALoAuthors rest;
public Cons(Author first, ALoAuthors rest){
this.first = first;
this.rest = rest;
}
Trang 6– Because every class in Java extends the class
Trang 7Abstracting over data definitions with object
The data definition for the Java classes is:
public abstract class ALoObject {
public class ConsLoObject {
private Object first;
privet ALoObject rest;
ConsLoObject( Object first, ALoObject rest){
this.first = first;
this.rest = rest;
}
}
Trang 8Validating for every list
• We now must validate that every list from our original examples can be represented as a list of Objects
• // example for a list of book
Book b1 = new Book("Call of the Wild", 10);
Book b2 = new Book("The Sea-Wolf", 12);
Book b3 = new Book("HtDP", 55);
ALoObject blist = new ConsLoObject(b2,
new ConsLoObject(b3, new MTLoObject()));
Trang 9Validating for every list
• // example for a list of Author
Author jackL = new Author("Jack London", 1876); Author dsteel = new Author("Danielle Steel", 1955); ALoObject authors = new ConsLoObject(jackL,
new ConsLoObject(dsteel,
new MTLoObject()));
Trang 10Manipulating in abstract list
• Q: count the number of objects in the list
Trang 11Manipulating in abstract list (cont)
• Q: Comparing the two contains methods from the
problem with stations and routes ,it is clear that:
– The same code is used to determine whether a list of
Routes contains a given Route as the code to determine whether a list of Stations contains a given Station
– The only difference is in the method header: in one case the method parameter is an instance of Route, in the other case it is an instance of Station.
– However, any instance of Route and any instance of Station
is also of type Object
Trang 12Manipulating in abstract list (cont)
public boolean contains(Object that) {
return this.first.equals(that) || this.rest.contains(that);
}
Trang 13• Exercise 1.0.1 Design a test suite that will
define several lists of Objects that contain only Book objects and use them to test the
methods count and contains.
• Do the same for lists of Shape objects.
that removes a given object from a list of
objects Test your method on the classes of
Books, and classes of Shapes.
Trang 14Abstracting over Data Definitions
with Interfaces
(part 1)
Trang 15Class diagram
<<abstract>>
ALog +double totalDistance() self-referential
ConsLog -Entry first
-ALog rest +double totalDistance()
+double totalDistance()
Trang 16-ALoBook rest +double totalPrice()
+double totalPrice()
Trang 17Take a look on codepublic class Entry {
private Date date;
private double distance;
private int durationInMinutes;
private String postRunFeeling;
public double totalDistance() {
return this.first getDitance() +
private String title;
private int publishYear;
private double price;
} }
Trang 18Take note
• The structure of the methods is the same, that
measures some total value of all items in the list
– The value in Entry is the distance
– The valuein Book is the price of a book
• However, the name of the field in each class that
extracts the value of the individual item is different in each case.
– It is posible to ask each class to provide getValue method that would return the desired value ?
• We could rename the method to totalValue The
resulting methods are almost the same.
Trang 19Take a look on code
public double totalValue() {
return this.first.getValue() +
//class MTLoBookpublic double totalValue() { return 0.0;
}//class ConsLoBookpublic double totalValue() {return this.first.getValue() + this.rest.totalValue();
}}
Trang 20Abstract with Object
• We can replace a list of Book and a list of Entry by a list of Object.// class ALoObject
public abstract double totalValue(){
Public double totalValue() {
return this.first.getValue() + this.rest.totalValue();
}
}
Trang 21Take note
• The program code in the class ConsLoObject
getValue().
• Q: How to solve this problem?
Trang 22same role (method).
Trang 23Solution (cont)
• In our case, we define Interface IValuable that declares double
getValue() method
public interface IValuable {
public double getValue();
Trang 24Exercise
• Exercise 2.0.3 Design the tests for the method totalValue
that will consume a list of Books
• Design a similar test for a list of Shape objects
• Exercise 2.0.4 Develop the method onlyTheBest that creates
a new list of objects, selecting only those that have a value
greater than some threshold specified by the user.
• Exercise 2.0.5 Develop the method hasValue that
determines whether there is an item in this list that has a
value lower than some value specified by the user.
• Exercise 2.0.6 Develop the method allFine that determines whether all objects in this list have a value greater than some threshold specified by the user.
Trang 25Relax &
… Do Exercises …
G O O D JOB! Too much hard exercises now
Try again, never stop practicing!
Trang 26Abstracting over Data Definitions
with Interfaces
(part 2)
Trang 27New requirement
• The bookstore manager would like to have a
published
• The runner would like to see the log with
covered in each run, from the shortest to the longest distance
• Q: Remind sort problem.
Trang 28Take a look on code
//Class ALog
public abstract ALog sortByDistance();
protected abstract ALog insertInDistanceOrder(Entry that);
//Class MTLog
public ALog sortByDistance() {
return this;
}
protected ALog insertInDistanceOrder(Entry that) {
return new ConsLog(that, this);
Trang 29Take a look on code (cont)
//Class ALoBook
public abstract ALog sortByPubishYear();
protected abstract ALog insertInYearOrder(Book that);
//Class MTLoBook
public ALoBook sortByPubishYear () {
return this;
}
protected ALoBook insertInYearOrder(Book that) {
return new ConsLoBook(that, this);
}
//Class ConsLog
public ALoBook sortByPubishYear () {
return this.rest.sortByPubishYear ().insertInYearOrder(this.first);
Trang 30Take note
• If we rename the classes to represent a list of Objects and change the method names in the
solutions become nearly identical
• The only lines where the differences are not
merely cosmetic are
– if ( that.hasDistanceShorterThan(this.first) )
– if ( that.hasYearSoonerThan(this.first) )
Trang 31Interface Comparable
• In general, here we want to compare some information recorded in the this.first object with similar information recorded in the object that is the argument to this function
• Java libraries include the interface Comparable defined as follows:
interface Comparable{
// compare this object with the given object
// produce negative result if this is 'smaller' than the given object
// produce zero if this object is 'the same' as the given object
// produce positive result if this is 'greater' than the given object
int compareTo (Object obj);
}
• Obviously, it is up to the implementing class to decide how to compare two items Let us implement the compareTo method for the class Book and for the class Entry
Trang 32Entry e1 = new Entry(d1, 5.0, 25,"Good");
Entry e2 = new Entry(d2, 3.0, 24,"Tired");
Entry e3 = new Entry(d3, 26.0, 156,"Great"); e1.compareTo(e2); // should be > 0
e2.compareTo(e3); // should be < 0
e2.compareTo(e2); // should be = 0
Trang 33compareTo in class Entry
• In the class Entry we modify the purpose, but the header
must be the same as defined in the interface:
• //compare the distance recorded in this entry with the given entry
public class Entry implements IValuable, Comparable {
…
int compareTo(Object obj){
return this.distance - ((Entry)obj).distance;
}
}
Trang 34Book b1 = new Book("HtDP", 2000, 55);
Book b2 = new Book("Call of the Wild", 1995, 10);
Book b3 = new Book("The Sea-Wolf", 1999, 12); b1.compareTo(b2); // should be > 0
b2.compareTo(b3); // should be < 0
b2.compareTo(b2); // should be = 0
Trang 35compareTo in class Book
• In the class Book we modify the purpose, but the header must
be the same as defined in the interface:
• // compare the publication year of this book with the given book
public class Book implements IValuable, Comparable {
…
int compareTo(Object obj){
return this.year - ((Book)obj).year;
}
}
Trang 36Abstract with Object
//Class ALoObject
public abstract ALoObject sort();
protected abstract ALog insert(Object that);
//Class MTLoObject
public ALoObject sort() {
return this;
}
protected ALoObject insert(Object that) {
return new ConsLoObject (that, this);
Trang 37• Exercise 2.0.7 Modify the way the class Book implements the
the sort works correctly
• Exercise 2.0.8 Develop the method isSorted that determines whether a
list of Objects that implement Comparable interface is sorted
• Exercise 2.0.9 The class String implements the Comparable interface to
allow the comparison of strings according to the lexicographical ordering Modify the class Book so that the compareTo method compares the books
by their title and then sort the books in lexicographical order
• Exercise 2.0.10 Modify the way the class Entry implements the
Hint: Recall methods for the class Date developed earlier
Trang 38Objects that represent functions
Trang 39New requirement
• Recall last exercise, book manager wants to sort all book accoding to 3 criteria: their
publish year, their price, their title.
• We need to define 3 different ways of sorting
a list of books, but in each case we have to
method in class Book)
Trang 40• We first define an interface that contains a method
interface Comparator{
int compare(Object obj1, Object obj2);
}
• For each of the three ways of comparing the books,
we can now define a new class that implements this interface The class has no fields , and defines only
Trang 413 classes implement interface
// compare two books by the year published
public class ByYear implements Comparator{
public int compare(Object obj1, Object obj2){\
return ((Book)obj1).getYear - ((Book)obj2).getYear;
}
}
// compare two books by price
public class ByPrice implements Comparator{
public int compare(Object obj1, Object obj2){
return ((Book)obj1).getPrice - ((Book)obj2).getPrice;
}
}
// compare two books by title
public class ByTitle implements Comparator{
public int compare(Object obj1, Object obj2){
return ((Book)obj1).getTitle.compareTo(((Book)obj2).getTitle); }
}
Trang 42Abstract with Object
Now in sort method, we add a parameter , comparable, which tells us the citerion to sort.
//Class ALoObject
public abstract ALoObject sort( Comparable cmp );
protected abstract ALog insert(Object that, Comparable cmp );
//Class MTLoObject
public ALoObject sort(Comparable cmp) {
return this;
}
protected ALoObject insert(Object that, Comparable cmp) {
return new ConsLoObject (that, this);
Trang 43TestingBook b1 = new Book("Call of the Wild", 10);
Book b2 = new Book("The Sea-Wolf", 12);
Book b3 = new Book("HtDP", 55);
ALoObject blist = new ConsLoObject(b1, new ConsLoObject(b2,
new ConsLoObject(b3,
new MTLoObject())));
ByYear bby = new ByYear();
ByPrice bbp = new ByPrice();
ByTitle bbt = new ByTitle();
// sort the list of books by year
Trang 44Exercise
using the three different versions of the Comparator object.
by comparing two Shape objects by their area Test the sort method on the list of Shape objects using the Comparator instance from the class ByArea.
• Repeat this exercise to sort the Shape objects by their distance to origin.
• Repeat this exercise once more to sort the Shape objects by the size of their
bounding box.
the signature
boolean choose(Object obj)
• Define the method filter for the class hierarchy that represents a list of Objects that produces a new list that contains those objects for which the method choose produces true value.
• Test your method by implementing several variants of the classes that implement the IChooser interface for the classes of Book and Shape objects
Trang 45Relax &
… Do Exercises …
G O O D JOB! Too much hard exercises now
Try again, never stop practicing!