Sunteți pe pagina 1din 6

Abstract superclasses

Superclasses are more general, or abstract, then their


COM6050 subclasses
Java and UML for Programmers Towards the top of a hierarchy classes are often more of a


basis for derived classes rather than a class with specific
Lecture 7: Interfaces and Abstract instances

Classes Consider the following inheritance relationships:


Person

Steve Renals
http://www.dcs.shef.ac.uk/ sjr/com6050

Employee Student
24.10.2002
COM6050 / Lecture 7 – p.1/21 Why bother with the person superclass? COM6050 / Lecture 7 – p.3/21

Objectives Abstract Person class


Abstract classes Some attributes make sense for every person, eg name.



Interfaces Introducing a person superclass lets us factor out the


getName method further up the hierarchy


Generic programming


Suppose we have a method getDescription which outputs


Documentation using Javadoc


the following strings for Student and Employee:


A professor of Physics with a salary of
Reading Core Java, vol 1, chapters 5 and 6.
$40,000
Effective Java, chapter 4.
A second year PhD student in English
This easy to implement for the subclasses. But what about
the parent Person class?
Solution: don’t implement the method in person:



abstract class Person . . .
public abstract String getDescription();

COM6050 / Lecture 7 – p.2/21 COM6050 / Lecture 7 – p.4/21


Abstract classes Interfaces
If you declare a method with the abstract keyword, an An interface describes what a class does, but not how it


implementation is not necessary does it
Any class with one or more abstract methods must be A class can implement one or more interfaces. Objects of


declared abstract these classes can then be used anytime something
Abstract classes can also have concrete data and methods conforming to the interface is required
- eg, getName can be implemented in Person Regard an interface as a set of requirements for a class


Think of abstract methods as placeholders to implemented The idea of separating interface from implementation is a


in concrete subclasses powerful one: it enables classes to be constructed that can
A class can be declared abstract even if it has no abstract operate on objects of any type, so long as they implement
methods the appropriate interface

If a class is declared abstract, no objects of that class can


be instantiated
COM6050 / Lecture 7 – p.5/21 COM6050 / Lecture 7 – p.7/21

Abstract Class Example Interface example: sorting


The method Arrays.sort promises to sort an array of objects


// Assume Employee and Student extend abstract class Person if the objects belong to a class that implements the
Person[ ] people = new Person[2];
Comparable interface
people[0] = new Employee(. . .)
people[1] = new Student(. . .) Employee staff[ ] = new Employee[10];
... ...
for(int i = 0; i people.length; ++i)


Arrays.sort(staff);
// p.getDescription() is never undefined since all instances
// must be of a concrete class The Comparable interface:


System.out.println(people[i].getName() + ": "


+ people[i].getDescription()); public interface Comparable
int compareTo(Object other);
If the abstract method was not declared in Person, then could


not invoke getDescription() without a cast.


A class implementing Comparable must therefore provide a


compareTo method
COM6050 / Lecture 7 – p.6/21 COM6050 / Lecture 7 – p.8/21
Interfaces Properties of Interfaces
Interfaces can have zero or more methods, and can also Interfaces are not classes, and cannot be instantiated:


define constants x = new Comparable(); // ERROR!

Interfaces never have instance fields You can declare interface variables:


Interfaces never implement methods
Comparable x; // OK
An interface is a promise, or a contract: a class
x = new Employee(. . .); // OK if Employee implements Comparable
implementing an interface must implement the methods
declared in the interface Can use instanceof to check if an object implements an


To declare that a class implements an interface, use the interface:
implements keyword: if (x instanceof Comparable) . . .
class Employee implements Comparable Classes can implement multiple interfaces, eg:


Interfaces are required due to strong typing: when making public class Employee implements Comparable, Cloneable ...
a method call the compiler must know the method exists.
COM6050 / Lecture 7 – p.9/21 COM6050 / Lecture 7 – p.11/21

Interface example: Employee class Interfaces vs Abstract Classes


Why not make Comparable an abstract class?





public class Employee implements Comparable public abstract class Comparable
... public abstract int compareTo(Object obj);

// sort by pay rate




public int compareTo(Object obj)


Employee e = (Employee) obj; public class Employee extends Comparable
...


// can’t return (payRate - e.payRate) since they are floating point public int compareTo(Object obj) ...
if(payRate e.payRate) return 1;


Problem: a class can only extend a single class, so this is not allowed:

if(payRate e.payRate) return 1;





public class Employee extends Comparable, Person
return 0;
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.10/21 COM6050 / Lecture 7 – p.12/21


Cloning and copying Summary
Interfaces and abstract classes both enable types to be


Copying Cloning
Employee
Employee defined with multiple implementations
original

For a class C to implement an abstract class A, C must be


copy
original a subclass of A
copy
A class C can implement an interface B, by implementing


Employee

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
Employee orig = new Employee("Bill Gates", 100000);
Interfaces are ideal for mixins: types (such as Comparable)


Employee copy = orig;
copy.increasePayRate(10000); // increases orig too! that a class may implement in addition to its primary type
With interfaces non-hierarchical type frameworks are


COM6050 / Lecture 7 – p.13/21
possible COM6050 / Lecture 7 – p.15/21

Abstract classes can provided default implementations


(sometimes useful)
Cloning How to insert javadoc comments
Clone using the clone method inherited from Object: The javadoc utility extracts information for every:
Employee copy = (Employee)orig.clone();
Package


But clone is protected method, so cannot simply call it
Public class


Object.clone() is protected because it copies objects field
Public interface


by field: OK for primitive types, but only copies references
Public or protected method

for object types. This is a problem for objects that contain
references to mutable objects. Public or protected variable or constant


Solution: (1) redefine clone as a public method; and (2) Thus you should supply a comment for each of these features
implement Cloneable interface
Redefining clone may involve calling clone on all object
instance fields (providing they are also Cloneable)
Cloneable is a “tagging” interface since it has no methods;
but it does allow the use of instanceof COM6050 / Lecture 7 – p.14/21 COM6050 / Lecture 7 – p.16/21
Javadoc Comments Javadoc: Method Comments
A comment is placed immediately above the feature it
describes /**
* Reads a fixed length string from an output stream
A documentation comment starts with /** and ends with */ *
* @param size length of string to read (may be terminated early by 0)
Each documentation comment starts with free-form text
* @param in code DataInput /code stream


followed by tags
* @return string read from stream
The first sentence of the free-form text should be a * @exception IOException if an error occurs
summary statement. This will be automatically extracted by */
public static String readFixedLengthString(int size, DataInput in)
javadoc


throws IOException
You can use HTML modifiers such as i . . . /i ,


. . .
b . . . /b , etc. Don’t use heading h1 or rule hr .



(NB @throws and @exception do the same thing)
A tag starts with @ such as @author and @param

COM6050 / Lecture 7 – p.17/21 COM6050 / Lecture 7 – p.19/21

Javadoc: Class and interface comments Running javadoc


On unix:
/**
mkdir JavaDoc # if it doesn’t exist
* The code TextRetrieval /code interface provides a way to access


* create and access a document archive using free-text retrieval methods.


javadoc -d JavaDoc *.java
* It provides methods for building an index ( code indexDocuments /code ),


* clearing the index ( code clear /code ), # or




* querying the document index ( code getRelevantDocumentsAnd /code and javadoc -d JavaDoc packageName


* code getRelevantDocumentsOr /code ) and obtaining document statistics




* ( code getNumWords /code , code getNumDocs /code ).




*
* @author a href=“mailto:sjr@dcs.shef.ac.uk“ Steve Renals /a


* @version Last modified: 2001-02-23 15:25:50 GMT (sjr)




*/


public interface TextRetrieval


. . .

COM6050 / Lecture 7 – p.18/21 COM6050 / Lecture 7 – p.20/21


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

S-ar putea să vă placă și