Beruflich Dokumente
Kultur Dokumente
Interfaces
Interfaces define a standardized set of commands that a class will obey
The interface definition states the names of the methods and their return types and argument
signatures
• there is no executable body for any method - that is left to each class that implements the
interface
Once a class implements an interface, the Java compiler knows that an instance of the class will
contain the specified set of methods
• therefore, it will allow you to call those methods for an object referenced by a variable
whose type is the interface
Implementing an interface enables a class to be "plugged in" in any situation that requires a
specific behavior (manifested through the set of methods)
An analogy: a serial interface on a computer defines a set of pin/wire assignments and the control
signals that will be used
• the actual devices that can be used may do entirely different tasks: mouse, modem, etc.
• but they are all controlled through the same digital instruction mechanism; the individual
wires are specified to carry specific signals
Using an interface rather than inheritance to specify a certain set of methods allows a class to
inherit from some other class
• in other words, if a class needs two different sets of methods, so it can behave like two
different types of things, it could inherit one set from class A, and use an interface B to
specify the other
• you could then reference one of these objects with either an A reference or a B reference
Interfaces can also specify constants that are public, static, and final
• define it like a Java class, in its own file that matches the interface name
• use the keyword interface instead of class
• declare methods using the same approach as abstract methods
o note the semicolon after each method declaration - and that no executable code is
supplied(and no curly braces)
o the elements will automatically be public and abstract, and cannot have any other
state; it is OK to specify those terms, but not necessary (usually public is specified
and abstract is not - that makes it easy to copy the list of methods, paste them into
a class, and modify them )
• The access level for the entire interface is usually public
o it may be omitted, in which case the interface is only available to other classes in
the same package (i.e., in the same directory)
o note, for the sake of completeness, there are situations where the interface
definition could be protected or private; these involve what are called inner
classes
Syntax
[modifiers] interface InterfaceName {
// declaring methods
// defining constants
Example:
This interface requires only one method. Any class implementing Printable must contain a public
void printall() method in order to compile
Because the above interface is defined as public, its definition must be in its own file, even
though that file will be tiny
An interface definition may also define properties that are automatically public static final - these
are used as constants
Implementing Interfaces
A class definition may, in addition to whatever else it does, implement one or more interfaces
Once a class states that it implements an interface, it must supply all the methods defined for that
interface, complete with executable code
• note: it actually does not have to implement all of them, but in that case the class cannot
be instantiated- it must be declared as an abstract class that can only be used as a base
class (where some derived class would then fully implement the interface)
To implement an interface:
• add that the class implements the interface to the class declaration
• add the methods specified by the interface to the body of the class
o note that you do need to specify the access terms on methods in a class that
implements an interface
Syntax
[modifiers] class ClassName implements InterfaceName {
It is important to note that a class may implement an interface in addition to whatever else it
might do, so it could have additional properties and methods not associated with the interface
A class may implement more than one interface - that merely adds to the list of required methods
Syntax
[modifiers] class ClassName implements Interface1Name, Interface2Name {
This file contains two classes with package access. Both implement the Printable interface, but
are otherwise not related. Stock has another method not related to Printable.
Since a class that implements an interface is a class in all other respects, you can create a
reference variable for that class, as usual
You can also create a reference variable whose type is the interface name
• only the methods defined in the interface are visible through a variable whose type is the
interface
o if you do this, the only things you can access with that variable are the interface
methods
o for a Printable variable containing a Stock instance, the sell method is not visible,
since it is not declared in Printable
• any constants defined by the interface can be accessed without a prefix from code within
the class, since implementing the interface makes them part of this class
• for using a variable whose type is an interface, the same situations apply for as were
discussed in the section on inheritance
Syntax
[modifiers] InterfaceName variableName;
Example:
or
pr = s;
or
pr = new Person();
• note that you cannot call any of the additional methods that are not defined by the
interface
Code Sample: Java-Interfaces/Demos/PrintableTest.java
public class PrintableTest {
public static void main(String[] args) {
Person p = new Person();
Stock s = new Stock();
p.printAll();
s.printAll();
Printable pr;
pr = p;
pr.printAll();
pr = s;
pr.printAll();
}
}
Code Explanation
• we cannot directly call the sell() method when pr refers to a Stock, since
the compiler would not associate it with a variable whose type was Printable
Note: to compile this, use *.java; since the name of the file containing Stock and Person is
PrintableThings.java, the compiler won't be able to find those classes, since it would be looking
for Person.java and Stock.java.
Note: you can test the type of object actually contained in an interface reference, and typecast it
back to that type
• the new interface then adds properties and methods to the existing (base) definition
• a class that implements the new interface must implement all methods from the base
interface as well as all the additional methods from the new interface definition
The following interface extends the Printable interface and adds another required method (the
new method overloads printAll to print to a specified destination instead of to System.out):
It turns out that our hypothetical system is to be used for all payments our company makes, not
just payroll checks- things like invoices will be paid through the system as well
• an object that can generate an event maintains a list of objects that would like to listen for
that event (they will be notified when the event occurs by having one of their methods
called)
• the object that generates the event fires it by going through its list of objects that want to
handle the event, and calling a specified interface method for each object
• a class may handle an event if it implements the interface that is expected for that event -
therefore it will have the specified method
• you register an object to handle an event by passing a reference to it to the event-
generating object's method that adds a handler
The ActionListener interface is used for GUI events like button clicks
• the event is fired by the GUI object calling the actionPerformed method for any
registered listeners (the code to do this is already built into the GUI classes, and the Java
API defines the interface shown below)
• it can either register itself with the event-generating object, or code outside the class can
register it - the example below shows how it would register itself using this
For the class that fires the event, registering is done with the addActionListener(ActionListener)
method, which receives a reference to an ActionListener object
For the sake of completeness, when the listener interface has multiple methods, there are often
abstract classes that implement most or all of the methods as do-nothing methods - so that all you
need to do is extend the class and implement the methods that you choose
• this is particularly useful for gaining the add and remove listener logic, which is
implemented in the base class
The Swing classes contain a component called JTable, which displays a spreadsheet-like grid
You can see the conversation that will take place between the controller and the model
• the controller will ask the model for the number of rows and columns, and, with that
information, ask for the value at each location
• it will ask for the type of data with getColumnClass, so it can determine from its settings
how to display the values (instances of Number, which Integer, Double, etc., extend, get
right-aligned, Boolean columns use a check box, all others get left-aligned - these settings
are configurable)
• it will get a heading for each column with getColumnName
• if a cell is double-clicked, it can ask if the cell is editable with isCellEditable
o if it is, when the user is done editing, it can put the new data into the model using
setValueAt
class TableConsole {
TableModel model;
class TableHTML {
TableModel model;
For getValueAt, we pick an array based on the column number, and return the element at the row
index.
getColumnClass returns a class object that matches the type of data for each array.
isCellEditable returns false, and setValueAt does nothing, because our model is not editable.
We then have three possible views of the data: a Swing GUI view that uses a JTable, a console
view that prints column-aligned data, and an HTML view that produces HTML code to the
console (you can copy that and paste it into a file to view in a browser, like in tablemodel.html).
Since the JTable is the whole reason TableModel exists, it knows what to do with the model. The
TableConsole and TableHTML view objects have to explicitly call the appropriate methods in
order to display the data.
Marker Interfaces
It is actually possible to have an interface that requires no methods at all! This creates what is
called a marker interface
A declaration that a class implements the interface makes it an instance of that interface, so that
it can be passed as a parameter to a method expecting an instance of the interface, or as a return
value from a method that declares it returns an instance of the interface.