Post on 14-Dec-2015
“AP Computer Science with .NET and J#”
Lecture 13: Interfaces and Interface-based Programming
Microsoft .NET Workshops for Teachers
13-3MicrosoftAP Computer Science with .NET and J#
Workshop Track
Lecture Topic
7 Algorithms and Algorithm Analysis
8 Debugging and Exception Handling
9 Applying Object-oriented Design Principles in Your Classes
10 Using Inheritance to Design a Set of Classes
11 MBS CS: the Marine Biology Simulation Case Study
12 Extending the MBS CS
13 Interfaces and Interface-based Programming
14 Extending the MBS CS, Part 2
15 Stacks, Queues and Invariants
16 Linked Data Structures and the Linked-list
17 Trees and Recursion
18 Collection Classes and Iteration
19 Additional Resources and Ideas
13-4MicrosoftAP Computer Science with .NET and J#
Lecture — Objectives
“Good object-oriented programming is really about good object-oriented design. And good OOD is all about making things easier for ourselves, as well as for our class users…”
• Topics:– Design by contract
– Interfaces
[ Joe Hummel, Lake Forest College ][ Joe Hummel, Lake Forest College ]
13-6MicrosoftAP Computer Science with .NET and J#
Motivation
• We program by relying on "contracts"– i.e. agreements between objects
– "Object X agrees to do Y, so I'll call X when I need to do Y"
java.io.FileReader file = new java.io.FileReader("…");java.io.BufferedReader reader = new java.io.BufferedReader(file);
s = reader.readLine();
java.io.FileReader file = new java.io.FileReader("…");java.io.BufferedReader reader = new java.io.BufferedReader(file);
s = reader.readLine();
public class BufferedReader{ . . .
public String readLine() { . . . }
public class BufferedReader{ . . .
public String readLine() { . . . }
13-7MicrosoftAP Computer Science with .NET and J#
Design by Contract
• Design by contract formalizes this process– design first
– implement second
• Advantages?
– encourages "think before you code“ for better designs
– classes that implement the same contract are interchangeable — i.e. “plug-compatible” — yielding a more flexible, easier to evolve system
– enforces a consistent design across a set of classes (much like inheritance), making it easier to program against these classes — can you say polymorphism!
13-9MicrosoftAP Computer Science with .NET and J#
Interfaces
• Interfaces are a formal way of specifying contracts• An interface = a set of method signatures
– representing the contract between two or more parties
– pure design, no data / code
public interface SomeInterfaceName{ public void Method1(); public int Method2(int x, String y); . . .}
public interface SomeInterfaceName{ public void Method1(); public int Method2(int x, String y); . . .}
13-10MicrosoftAP Computer Science with .NET and J#
Conceptual view
• Here's how to visualize what's going on:
"server"(object performing
service according to interface contract)
"client"(object requesting
service)
Interface
– "client" uses interface to communicate with server
– "server" implements interface to fulfill contract
13-11MicrosoftAP Computer Science with .NET and J#
Example
• Sorting and binary search• These algorithms are a part of the Java Class Library
– great examples of the power of polymorphism — one sort and one binary search for all objects in Java!
– use an interface to communicate with objects…
sort( ) objectobjectobject
binarySearch( ) objectobjectobject
13-12MicrosoftAP Computer Science with .NET and J#
Working with Interfaces
• Working with interfaces involves 3 steps:
1. Define the interface
2. Implement the interface
3. Program against the interface
• Let’s work through the sorting example…
13-13MicrosoftAP Computer Science with .NET and J#
(1) Comparable Interface
• Java’s Comparable interface formalizes what it means to compare 2 objects
• Defines a compare method that returns an integer:– < 0 means this object < parameter obj
– = 0 means this object = parameter obj
– > 0 means this object > parameter obj
public interface Comparable { public int compareTo(Object obj); }
public interface Comparable { public int compareTo(Object obj); }
if (s1.compareTo(s2) < 0) ...if (s1.compareTo(s2) < 0) ...
13-14MicrosoftAP Computer Science with .NET and J#
(2) Sortable Objects Implement Comparable
• To fulfill contract, objects must implement Comparable:
public class BankCustomer implements Comparable{ private String firstName, lastName; . . .
public int compareTo(Object obj) { // make sure we are comparing apples to apples… BankCustomer other = (BankCustomer) obj; int diff; diff = this.lastName.compareTo(other.lastName); if (diff == 0) // last names are the same, so look at first names: diff = this.firstName.compareTo(other.firstName);
return diff; }
public class BankCustomer implements Comparable{ private String firstName, lastName; . . .
public int compareTo(Object obj) { // make sure we are comparing apples to apples… BankCustomer other = (BankCustomer) obj; int diff; diff = this.lastName.compareTo(other.lastName); if (diff == 0) // last names are the same, so look at first names: diff = this.firstName.compareTo(other.firstName);
return diff; }
studentstudentBankCustomer
13-15MicrosoftAP Computer Science with .NET and J#
(3) Writing a Generic Sort()
• Now we can sort any list of Comparable objects!– For simplicity, here’s Selection sort:
public static void sort(ArrayList list){ for (int i = 0; i < list.size(); i++) { for (int j = i+1; j < list.size(); j++) { Comparable obj1; Object obj2;
obj1 = (Comparable) list.get(i); obj2 = list.get(j);
if (obj1.compareTo(obj2) > 0) // swap! { list.set(i, obj2); list.set(j, obj1); } }//inner }//outer}
public static void sort(ArrayList list){ for (int i = 0; i < list.size(); i++) { for (int j = i+1; j < list.size(); j++) { Comparable obj1; Object obj2;
obj1 = (Comparable) list.get(i); obj2 = list.get(j);
if (obj1.compareTo(obj2) > 0) // swap! { list.set(i, obj2); list.set(j, obj1); } }//inner }//outer}
13-17MicrosoftAP Computer Science with .NET and J#
Java’s Predefined Sort and Search Methods
• As long as our objects implement Comparable, we can take advantage of Java’s sort and binarySearch methods:
ArrayList bank = new ArrayList();bank.add( ... );bank.add( ... ); . . .
java.util.Collections.sort(bank);
int i;BankCustomer c; // we need a temporary object holding search criteria to pass to binary search:c = new BankCustomer(firstname, lastname, 0, null, null);
i = java.util.Collections.binarySearch(bank, c);if (i >= 0) System.out.println("Found in arraylist at index " + i);else System.out.println("Not found!");
ArrayList bank = new ArrayList();bank.add( ... );bank.add( ... ); . . .
java.util.Collections.sort(bank);
int i;BankCustomer c; // we need a temporary object holding search criteria to pass to binary search:c = new BankCustomer(firstname, lastname, 0, null, null);
i = java.util.Collections.binarySearch(bank, c);if (i >= 0) System.out.println("Found in arraylist at index " + i);else System.out.println("Not found!");
13-19MicrosoftAP Computer Science with .NET and J#
Hey, what about Linear Search?
• Note that binary search only works if objects are sorted– Binary search is fast (O(lgn)), but sorting is slow (O(nlgn))
• Suppose we only need to do 1 search, and data isn’t sorted?– Then a linear search (O(n)) makes more sense
ArrayList bank; . . .
int i;BankCustomer c; // we need a temporary object holding search criteria to pass to linear search:c = new BankCustomer(firstname, lastname, 0, null, null);
i = bank.indexOf(c); // performs a linear searchif (i >= 0) System.out.println("Found in arraylist at index " + i);else System.out.println("Not found!");
ArrayList bank; . . .
int i;BankCustomer c; // we need a temporary object holding search criteria to pass to linear search:c = new BankCustomer(firstname, lastname, 0, null, null);
i = bank.indexOf(c); // performs a linear searchif (i >= 0) System.out.println("Found in arraylist at index " + i);else System.out.println("Not found!");
will *not* be found…
13-20MicrosoftAP Computer Science with .NET and J#
Overriding Equals
• Linear search is based on finding an object that is equal– And equality is defined by equals method, not compareTo...
– … so override default version inherited from Object class
public class BankCustomer implements Comparable{ private String firstName, lastName; . . .
public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false;
BankCustomer other = (BankCustomer)obj; return this.lastName.equals(other.lastName) && this.firstName.equals(other.firstName); }
public class BankCustomer implements Comparable{ private String firstName, lastName; . . .
public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false;
BankCustomer other = (BankCustomer)obj; return this.lastName.equals(other.lastName) && this.firstName.equals(other.firstName); }
13-22MicrosoftAP Computer Science with .NET and J#
Summary
• Interfaces are another powerful tool for OO design• Interfaces are used throughout Java
– effective use requires a solid understanding of OOD
– e.g. linear search is built-in, but you need to override equals()
– e.g. sorting & binary search are built-in, but you need to implement Comparable and compareTo()
• Use interfaces when:– You are designing a set of classes
– Classes adhere to the “acts-like” rule — a BankCustomer acts-like a sortable and searchable object
13-23MicrosoftAP Computer Science with .NET and J#
Resources
• Web site for slides, demos, associated lab exercises:
– http://blogs.msdn.com/daryllmc/default.aspx
– http://www.lakeforest.edu/~hummel/workshops-HS.htm
– https://www.mainfunction.com/home/training/
• Supplemental Reading:
– M. Weisfeld, “The Object-Oriented Thought Process” (language-neutral)
– D. West, “Object Thinking” (language-neutral)
– Sierra & Bates, “Head First Java”• Your students may really like this one, a very hip approach to learning Java
13-24MicrosoftAP Computer Science with .NET and J#
That’s it!
• Next up:
Lecture Topic
. .
14 Extending the MBS CS, Part 2
. .
. .
. .