1 Interface
Java’s interface
is a useful language mechanism for expressing an abstract data type (ADT).
1.1 Subtypes
A subtype is simply a subset of the supertype : ArrayList and LinkedList are subtypes of List . “B is a subtype of A” means “every B is an A.” In terms of specifications: “every B satisfies the specification for A.”
How will clients use this ADT as an interface? Here’s an example:
SomeInterface s = new Subtypes(true);
System.out.println("The first character is: " + s.charAt(0));
- This pattern breaks the abstraction barrier we’ve worked so hard to build between the abstract type and its concrete representations. Clients must know the name of the concrete representation class.
- Fortunately, (as of Java 8) interfaces are allowed to contain static methods, so we can implement the creator operation valueOf as a static factory method in the interface, as an example:
public interface MyString {
/** @param b a boolean value
* @return string representation of b, either "true" or "false" */
public static MyString valueOf(boolean b) {
return new FastMyString(true);
}
2 Generic Interfaces
public interface Set<E> {
// ...
- Generic interface, non-generic implementation.
public class CharSet implements Set<Character>{
//...
- Generic interface, generic implementation
public class HashSet<E> implements Set<E> {
//...
Reference
[1] 6.005 — Software Construction on MIT OpenCourseWare | OCW 6.005 Homepage at https://ocw.mit.edu/ans7870/6/6.005/s16/