Transcript Interfaces

Designing
Classes
Chapter 3
Contents
• Encapsulation
• Specifying Methods
• Java Interfaces
–
–
–
–
–
–
–
–
Writing an Interface
Implementing an Interface
An Interface as a Data Type
Generic Types Within an Interface
Type Casts Within an Interface Implementation
Extending an Interface
Interfaces Versus Abstract Classes
Named Constants Within an Interface
Contents
• Choosing Classes
– Identifying Classes
– CRC Cards
– The Unified Modeling Language
• Reusing Classes
Encapsulation
• Hides the fine detail of the inner workings of
the class
– The implementation is hidden
– Often called "information hiding"
• Part of the class is visible
– The necessary controls for the class are left visible
– The class interface is made visible
– The programmer is given only enough information
to use the class
Encapsulation
Fig. 3-1 An automobile's controls are visible to the
driver, but its inner workings are hidden.
Abstraction
• A process that has the designer ask what
instead of why
– What is it you want to do with the data
– What will be done to the data
• The designer does not consider how the
class's methods will accomplish their goals
• The client interface is the what
• The implementation is the how
Abstraction
Fig. 3-2 An interface
provides well-regulated
communication between a
hidden implementation and
a client.
Specifying Methods
• Specify what each method does
• Precondition
– Defines responsibility of client code
• Postcondition
– Specifies what will happen if the preconditions are
met
Specifying Methods
• Responsibility
– Precondition implies responsibility for guarantee
of meeting certain conditions
• Where to place responsibility
– Client? or …
– Method?
• Best to comment this clearly before method's
header
– Also good to have method check during
debugging
Specifying Methods
• Assertion is statement of truth about aspect
of a program's logic
– Like a boolean statement that should be true at a
certain point
• Assertions can be written as comments to
identify design logic
// Assertion: intVal >= 0
• Assert Statement
– assert
someVal < 0;
– If false, program execution terminates
Java Interface
• A program component that contains
– Public constants
– Signatures for public methods
– Comments that describe them
• Begins like a class definition
– Use the word interface instead of class
Writing an Interface
• Consider geometric figures which have both a
perimeter and an area
• We want classes of such objects to have such
methods
– And we want standardization signatures
• View example of the interface Measurable
Java Interface Example
• Recall class Name from previous chapter
• Consider an interface for the class Name
– View example listing
• Note
– Comments of method purpose, parameters, preand post-conditions
– Any data fields should be public, final, and static
– Interface methods cannot be final
Implementing an Interface
• A class that implements an interface must state so at
start of definition with implements clause
• The class must implement every method declared in
the interface
• Multiple classes can implement the same interface
• A class can implement more than one interface
Implementing an Interface
Fig. 3-3 The files for an interface, a class that implements
the interface, and the client.
An Interface as a Data Type
• An interface can be used as a data type
or …
Generic Types Within an Interface
• Recall class OrderedPair from Chapter 2
– Note the setPair method
• Consider an interface Pairable that
declares this method
A class that implements this interface could begin with the statement
The Interface Comparable
• Method compareTo compares two objects,
say x and y
–
–
–
–
Returns signed integer
Returns negative if x < y
Returns zero if x == y
Returns positive if x > y
The Interface Comparable
• Consider a class Circle
– Methods equals, compareTo
– Methods from Measurable
• View source code
• Note
– Implements Measurable interface
– Shown with two alternative versions of
compareTo
Extending an Interface
• Use inheritance to derive an interface from
another
• When an interface extends another
– It has all the methods of the inherited interface
– Also include some new methods
• Also possible to combine several interfaces
into a new interface
– Not possible with classes
Interfaces Versus Abstract Classes
• Purpose of interface similar to purpose of
abstract class
• But … an interface is not a base class
– It is not a class of any kind
• Use an abstract base class when
– You need a method or private data field that
classes will have in common
• Otherwise use an interface
Named Constants Within an Interface
• An interface can contain named constants
– Public data fields initialized and declared as
final
• Consider an interface with a collection of
named constants
– Then derive variety of interfaces that can make
use of these constants
Choosing Classes
• Look at a prospective system from a functional
point of view
• Ask
– What or who will use the system
– What can each actor do with the system
– Which scenarios involve common goals
• Use a case diagram
Choosing Classes
Fig. 3-4 A use case diagram for a registration system
Identifying Classes
• Describe the system
– Identify nouns and verbs
• Nouns suggest classes
– Students
– Transactions
– Customers
• Verbs suggest appropriate methods
– Print an object
– Post a transaction
– Bill the customer
Identifying Classes
Fig. 3-5 A description of a use case for adding a course
CRC Cards
• Index cards – each card represents one class
• Write a descriptive name for class at top
• List the class's responsibilities
– The methods
• Indicate interactions
– The collaborations
• These are CRC cards
"Class-Responsibility-Collaboration"
CRC Cards
Fig. 3-6 A class-responsibility-collaboration card
Unified Modeling Language
• Used to illustrate a system's classes and
relationships
• Provides a class diagram
– Class name
– Attributes
– Operations
Fig. 3-7 A class representation that can
be part of a class diagram.
Unified Modeling Language
Fig. 3-8 UML notation for a base class
Student and two derived classes
Unified Modeling Language
Fig. 3-9 A class
diagram showing
the base class
Student and two
derived classes
Unified Modeling Language
Fig. 3-10 Part of a UML class diagram
with associations.
Reusing Classes
• Much software combines:
– Existing components
– New components
• When designing new classes
– Plan for reusability in the future
– Make objects as general as possible
– Avoid dependencies that restrict later use by
another programmer
Interfaces
• A Java interface is a collection of abstract
methods and constants
• An abstract method is a method header
without a method body
• An abstract method can be declared using the
modifier abstract, but because all methods in
an interface are abstract, usually it is left off
• An interface is used to establish a set of
methods that a class will implement
Interfaces
interface is a reserved word
None of the methods in
an interface are given
a definition (body)
public interface Doable
{
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}
A semicolon immediately
follows each method header
Interfaces
• An interface cannot be instantiated
• Methods in an interface have public visibility by
default
• A class formally implements an interface by
– stating so in the class header
– providing implementations for each abstract method in the
interface
• If a class asserts that it implements an interface,
it must define all methods in the interface
Interfaces
public class CanDo implements Doable
{
public void doThis ()
implements is a
{
reserved word
// whatever
}
public void doThat ()
{
// whatever
}
// etc.
}
Each method listed
in Doable is
given a definition
Interfaces
• A class that implements an interface can
implement other methods as well
• In addition to (or instead of) abstract methods,
an interface can contain constants
• When a class implements an interface, it gains
access to all its constants
Interfaces
• An example of an interface in use
SecretTest.java
//********************************************************************
// SecretTest.java
Java Foundations
//
// Demonstrates the use of a formal interface.
//********************************************************************
public class SecretTest
{
//----------------------------------------------------------------// Creates a Secret object and exercises its encryption.
//----------------------------------------------------------------public static void main (String[] args)
{
Secret hush = new Secret ("Wil Wheaton is my hero!");
System.out.println (hush);
hush.encrypt();
System.out.println (hush);
hush.decrypt();
System.out.println (hush);
}
}
Encryptable.java
//********************************************************************
// Encryptable.java
Java Foundations
//
// Represents the interface for an object that can be encrypted
// and decrypted.
//********************************************************************
public interface Encryptable
{
public void encrypt();
public String decrypt();
}
Secret.java
//********************************************************************
// Secret.java
Java Foundations
//
// Represents a secret message that can be encrypted and decrypted.
//********************************************************************
import java.util.Random;
public class Secret implements Encryptable
{
private String message;
private boolean encrypted;
private int shift;
private Random generator;
//----------------------------------------------------------------// Constructor: Stores the original message and establishes
// a value for the encryption shift.
//----------------------------------------------------------------public Secret (String msg)
{
message = msg;
encrypted = false;
generator = new Random();
shift = generator.nextInt(10) + 5;
}
(more…)
Secret.java
//----------------------------------------------------------------// Encrypts this secret using a Caesar cipher. Has no effect if
// this secret is already encrypted.
//----------------------------------------------------------------public void encrypt ()
{
if (!encrypted)
{
String masked = "";
for (int index=0; index < message.length(); index++)
masked = masked + (char)(message.charAt(index)+shift);
message = masked;
encrypted = true;
}
}
(more…)
Secret.java
//----------------------------------------------------------------// Decrypts and returns this secret. Has no effect if this
// secret is not currently encrypted.
//----------------------------------------------------------------public String decrypt()
{
if (encrypted)
{
String unmasked = "";
for (int index=0; index < message.length(); index++)
unmasked = unmasked + (char)(message.charAt(index)-shift);
message = unmasked;
encrypted = false;
}
return message;
}
//----------------------------------------------------------------// Returns true if this secret is currently encrypted.
//----------------------------------------------------------------public boolean isEncrypted()
{
return encrypted;
}
(more…)
Secret.java
//----------------------------------------------------------------// Returns this secret (may be encrypted).
//----------------------------------------------------------------public String toString()
{
return message;
}
}
Interfaces
• A class can implement multiple interfaces
• The interfaces are listed in the implements clause
• The class must implement all methods in all
interfaces listed in the header
class ManyThings implements interface1, interface2
{
// all methods of both interfaces
}
Interfaces
• The Java standard class library contains many
helpful interfaces
• The Comparable interface contains one abstract
method called compareTo, which is used to
compare two objects
• We discussed the compareTo method of the String
class in Chapter 4
• The String class implements Comparable, giving us
the ability to put strings in lexicographic order
The Comparable Interface
• Any class can implement Comparable to provide a
mechanism for comparing objects of that type
if (obj1.compareTo(obj2) < 0)
System.out.println ("obj1 is less than obj2");
• The value returned from compareTo should be negative is
obj1 is less that obj2, 0 if they are equal, and positive if
obj1 is greater than obj2
• When a programmer designs a class that implements the
Comparable interface, it should follow this intent
The Comparable Interface
• It’s up to the programmer to determine what
makes one object less than another
• For example, you may define the compareTo
method of an Employee class to order employees
by name (alphabetically) or by employee number
• The implementation of the method can be as
straightforward or as complex as needed for the
situation
The Iterator Interface
• As we discussed in Chapter 4, an iterator is an
object that provides a means of processing a
collection of objects one at a time
• An iterator is created formally by implementing
the Iterator interface, which contains three
methods
• The hasNext method returns a boolean result –
true if there are items left to process
• The next method returns the next object in the
iteration
• The remove method removes the object most
recently returned by the next method
The Iterator Interface
• By implementing the Iterator interface, a
class formally establishes that objects of that
type are iterators
• The programmer must decide how best to
implement the iterator functions
• Once established, the for-each version of the
for loop can be used to process the items in
the iterator
Interfaces
• You could write a class that implements certain
methods (such as compareTo) without formally
implementing the interface (Comparable)
• However, formally establishing the relationship
between a class and an interface allows Java to
deal with an object in certain ways
• Interfaces are a key aspect of object-oriented
design in Java
Polymorphism via Interfaces
• An interface name can be used as the type of an object
reference variable
Speaker current;
• The current reference can be used to point to any
object of any class that implements the Speaker
interface
• The version of speak that the following line invokes
depends on the type of object that current is
referencing
current.speak();
Polymorphism via Interfaces
• Suppose two classes, Philosopher and Dog, both
implement the Speaker interface, providing
distinct versions of the speak method
• In the following code, the first call to speak
invokes one version and the second invokes
another
Speaker guest = new Philospher();
guest.speak();
guest = new Dog();
guest.speak();
Event Processing
• Polymorphism plays an important role in the
development of a Java graphical user interface
• As we’ve seen, we establish a relationship
between a component and a listener
JButton button = new JButton();
button.addActionListener(new MyListener());
• Note that the addActionListener method is
accepting a MyListener object as a parameter
• In fact, we can pass the addActionListener
method any object that implements the
ActionListener interface
Event Processing
• The source code for the addActionListener
method accepts a parameter of type
ActionListener (the interface)
• Because of polymorphism, any object that
implements that interface is compatible with the
parameter reference variable
• The component can call the actionPerformed
method because of the relationship between the
listener class and the interface
• Extending an adapter class to create a listener
represents the same situation; the adapter class
implements the appropriate interface already