Version2-4up - Fat GripzTitle Version2-4up.indd Created Date 5/14/2015 11:57:03 AM
07 Interfaces 4up
-
Upload
marco-paciucci -
Category
Documents
-
view
214 -
download
0
Transcript of 07 Interfaces 4up
-
8/8/2019 07 Interfaces 4up
1/6
COM6050
Java and UML for Programmers
Lecture 7: Interfaces and AbstractClasses
Steve Renalshttp://www.dcs.shef.ac.uk/ sjr/com6050
24.10.2002
COM6050 / Lecture 7 p.1/21
Objectives
Abstract classes
Interfaces
Generic programming
Documentation using Javadoc
Reading Core Java, vol 1, chapters 5 and 6.
Effective Java, chapter 4.
COM6050 / Lecture 7 p.2/21
Abstract superclasses
Superclasses are more general, or abstract, then their
subclasses
Towards the top of a hierarchy classes are often more of abasis for derived classes rather than a class with specific
instances
Consider the following inheritance relationships:
Person
Employee Student
Why bother with the person superclass?COM6050 / Lecture 7 p.3/21
Abstract Person class
Some attributes make sense for every person, eg name.
Introducing a person superclass lets us factor out the
getName method further up the hierarchy
Suppose we have a method getDescription which outputsthe following strings for Student and Employee:
A professor of Physics with a salary of
$40,000
A second year PhD student in English
This easy to implement for the subclasses. But what about
the parent Person class?
Solution: dont implement the method in person:
abstract class Person
. . .public abstract String getDescription();
COM6050 / Lecture 7 p.4/21
-
8/8/2019 07 Interfaces 4up
2/6
Abstract classes
If you declare a method with the abstract keyword, an
implementation is not necessary
Any class with one or more abstract methods must bedeclared abstract
Abstract classes can also have concretedata and methods
- eg, getName can be implemented in Person
Think of abstract methods as placeholders to implemented
in concrete subclasses
A class can be declared abstract even if it has no abstract
methods
If a class is declared abstract, no objects of that class can
be instantiated
COM6050 / Lecture 7 p.5/21
Abstract Class Example
// Assume Employee and Student extend abstract class Person
Person[] people = new Person[2];
people[0] = new Employee(.. .)
people[1] = new Student(.. .)
. . .
for(int i = 0 ; i
people.length; ++i)
// p.getDescription() is never undefined since all instances
// must be of a concrete class
System.out.println(people[i].getName() + ": "
+ people[i].getDescription());
If the abstract method was not declared in Person, then couldnot invoke getDescription() without a cast.
COM6050 / Lecture 7 p.6/21
Interfaces
An interface describes what a class does, but not how it
does it
A class can implement one or more interfaces. Objects ofthese classes can then be used anytime something
conforming to the interface is required
Regard an interface as a set of requirements for a class
The idea of separating interface from implementation is a
powerful one: it enables classes to be constructed that can
operate on objects of any type, so long as they implementthe appropriate interface
COM6050 / Lecture 7 p.7/21
Interface example: sorting
The method Arrays.sort promises to sort an array of objects
if the objects belong to a class that implements the
Comparable interface
Employee staff[] = new Employee[10];
. . .
Arrays.sort(staff);
The Comparable interface:
public interface Comparable
int compareTo(Object other);
A class implementing Comparable must therefore provide a
compareTo methodCOM6050 / Lecture 7 p.8/21
-
8/8/2019 07 Interfaces 4up
3/6
Interfaces
Interfaces can have zero or more methods, and can also
define constants
Interfaces never have instance fields Interfaces never implement methods
An interface is a promise, or a contract: a class
implementing an interface must implement the methods
declared in the interface
To declare that a class implements an interface, use the
implements keyword:
class Employee implements Comparable
Interfaces are required due to strong typing: when making
a method call the compiler must know the method exists.
COM6050 / Lecture 7 p.9/21
Interface example: Employee class
public class Employee implements Comparable
. . .
// sort by pay rate
public int compareTo(Object obj)
Employee e = (Employee) obj;
// cant return (payRate - e.payRate) since they are floating point
if(payRate
e.payRate) return 1;
if(payRate
e.payRate) return 1;
return 0;
COM6050 / Lecture 7 p.10/21
Properties of Interfaces
Interfaces are not classes, and cannot be instantiated:
x = new Comparable(); // ERROR!
You can declare interface variables:
Comparable x; // OK
x = new Employee(. . .); // OK if Employee implements Comparable
Can use instanceof to check if an object implements an
interface:
if (x instanceof Comparable) . . .
Classes can implement multiple interfaces, eg:
public class Employee implements Comparable, Cloneable
. . .
COM6050 / Lecture 7 p.11/21
Interfaces vs Abstract Classes
Why not make Comparable an abstract class?public abstract class Comparable
public abstract int compareTo(Object obj);
public class Employee extends Comparable
. . .
public int compareTo(Object obj)
. . .
Problem: a class can only extend a single class, so this is not allowed:
public class Employee extends Comparable, Person
But a class can extend a base class and implement one or more
interfaces: public class Employee extends Person implements Comparable
(Java does not permit multiple inheritance unlike C++ or Eiffel)
COM6050 / Lecture 7 p.12/21
-
8/8/2019 07 Interfaces 4up
4/6
Cloning and copying
Employeeoriginal
copy
Employee
Employee
original
copy
CloningCopying
Employee orig = new Employee("Bill Gates", 100000);
Employee copy = orig;
copy.increasePayRate(10000); // increases orig too!
COM6050 / Lecture 7 p.13/21
Cloning
Clone using the clone method inherited from Object:
Employee copy = (Employee)orig.clone();
But clone is protected method, so cannot simply call it
Object.clone() is protected because it copies objects field
by field: OK for primitive types, but only copies references
for object types. This is a problem for objects that contain
references to mutable objects.
Solution: (1) redefine clone as a public method; and (2)
implement Cloneable interface
Redefining clone may involve calling clone on all objectinstance fields (providing they are also Cloneable)
Cloneable is a tagging interface since it has no methods;
but it does allow the use of instanceofCOM6050 / Lecture 7 p.14/21
Summary
Interfaces and abstract classes both enable types to be
defined with multiple implementations
For a class C to implement an abstract class A, C must bea subclass of A
A class C can implement an interface B, by implementing
the required methods (following the contract of the
interface)
Existing classes can be easily modified to implement a new
interface: the type hierarchy is not changed Interfaces are ideal for mixins: types (such as Comparable)
that a class may implement in addition to its primary type
With interfaces non-hierarchical type frameworks are
possibleCOM6050 / Lecture 7 p.15/21
How to insert javadoc comments
The javadoc utility extracts information for every:
Package
Public class
Public interface
Public or protected method
Public or protected variable or constant
Thus you should supply a comment for each of these features
COM6050 / Lecture 7 p.16/21
-
8/8/2019 07 Interfaces 4up
5/6
Javadoc Comments
A comment is placed immediately above the feature it
describes
A documentation comment starts with /** and ends with */ Each documentation comment starts with free-form text
followed by tags
The first sentence of the free-form text should be a
summary statement. This will be automatically extracted by
javadoc
You can use HTML modifiers such as
i
. . .
/i
,
b
. . .
/b
, etc. Dont use heading
h1
or rule
hr
.
A tag starts with @ such as @author and @param
COM6050 / Lecture 7 p.17/21
Javadoc: Class and interface comments
/**
* The
code
TextRetrieval
/code
interface provides a way to access
* create and access a document archive using free-text retrieval methods.
* It provides methods for building an index (
code
indexDocuments
/code
),
* clearing the index (
code
clear
/code
),
* querying the document index (
code
getRelevantDocumentsAnd
/code
and
*
code
getRelevantDocumentsOr
/code
) and obtaining document statistics
* (
code
getNumWords
/code
,
code
getNumDocs
/code
).
*
* @author
a href=mailto:[email protected]
Steve Renals
/a
* @version Last modified:
2001-02-23 15:25:50 GMT (sjr)
*/
public interface TextRetrieval
. . .
COM6050 / Lecture 7 p.18/21
Javadoc: Method Comments
/**
* Reads a fixed length string from an output stream
*
* @param size length of string to read (may be terminated early by 0)
* @param in
code
DataInput
/code
stream
* @return string read from stream
* @exception IOException if an error occurs
*/
public static String readFixedLengthString(int size, DataInput in)
throws IOException
. . .
(NB @throws and @exception do the same thing)
COM6050 / Lecture 7 p.19/21
Running javadoc
On unix:
mkdir JavaDoc # if it doesnt exist
javadoc -d JavaDoc *.java
# or
javadoc -d JavaDoc packageName
COM6050 / Lecture 7 p.20/21
-
8/8/2019 07 Interfaces 4up
6/6
Exercises (1)
1. A programmer is designing a system for the manipulation of shapes.
Since a square is a rectangle, they decide make Square a subclass of
Rectangle. Is this a sensible design decision?
2. Following on from previous exercises, develop the Customer class so
that it implements the Comparable interface. Construct and sort an
array of Customers.
3. In the original Customer/Order scenario, consider adding a method
@toSummary()@ to the Customer, Order and Product classes. This
method is rather similar to @toString()@, except it gives much less
detailed information. Such a method could be implemented in two
ways: (a) using a common abstract class (eg AbstractCOP); (b) using
an interface (call it Summarizable). Implement and test both solutions
in Java. Which do you prefer?
COM6050 / Lecture 7 p.21/21