nter faces

21
8/12/2019 Nter Faces http://slidepdf.com/reader/full/nter-faces 1/21 nterfaces In this lesson, you will learn about interfaces and annotations. Lesson Goals  Learn about the concept of interfaces.  Define and write code using your own interfaces.  Use interfaces in the Java API. Interfaces  Interfaces  define a standardized set of commands that a class will obey. The commands are a set of methods that a class implements. 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" to 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. Note that:  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.

Upload: shazia-hassan

Post on 03-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 1/21

nterfaces

In this lesson, you will learn about interfaces and annotations.

Lesson Goals

  Learn about the concept of interfaces.

  Define and write code using your own interfaces.

  Use interfaces in the Java API.

Interfaces

 Interfaces define a standardized set of commands that a class will obey.

The commands are a set of methods that a class implements.

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 aninstance 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" to 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. Note that:

  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.

Page 2: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 2/21

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.

Creating an Interface Definition

To create an interface definition:

  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).

Page 3: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 3/21

o  Note, for the sake of completeness, there are situations where the

interface definition could be protected or private; these involve what

are calledinner classes.

12

34

5

6

78

[modifiers] interface InterfaceName { 

// declaring methods [public abstract] returnType methodName1(arguments); 

// defining constants [public static final] type fieldName = value; 

Code Sample:

Java-Interfaces/Demos/Printable.java1

2

3

public interface Printable { void printAll(); 

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 fields 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.

Page 4: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 4/21

  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. Note

that youdo need to specify the access terms on methods in a class that

implements an interface.

12

3

45

6

78

9

10

11

12

[modifiers] class ClassName implements InterfaceName { 

any desired fields 

// implement required methods [modifiers] returnType methodName1(arguments) { 

executable code } 

any other desired methods 

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 fields and methods not

associated with the interface.

 A class may implement more than one interface - that merely adds to the list

of required methods. Use a comma-separated list for the interface names.

1

2

34

[modifiers] class ClassName implements Interface1Name, Interface2Name { 

// must implement all methods from all implemented interfacse } 

Implementing Interfaces - Example

The complete example will use three separate files (the third file will be shown

shortly):

Page 5: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 5/21

Code Sample:

Java-Interfaces/Demos/Printable.java12

3

public interface Printable { void printAll(); 

Code Sample:

Java-Interfaces/Demos/PrintableThings.java1

2

34

5

67

8

9

1011

12

1314

15

16

17

181920

class Person implements Printable { private String name = new String("Bill"); private int age = 22; public void printAll() { 

System.out.println("Name is " + name + ", age is " + age); } 

} class Stock implements Printable { private String tickerSymbol = new String("XYZ"); private int shares = 100; private int currentPrice = 4000; // in pennies public void printAll() { 

System.out.println(tickerSymbol + " " + shares + " shares at " + currentPrice); 

System.out.println("Value: " + currentPrice * shares); } public void sell() { 

System.out.println(tickerSymbol + " sold"); 

} } 

This file contains two classes with package access. Since the classes are not

public, they can both be in the same file, and the file name does not need to

match either class name. This is done purely as a convenience; it is not a good

programming practice in general, but is sometimes useful if one class is highly

coupled  (interrelated) with the other, which is not the case here. Both classes

implement the Printable interface, but are otherwise not related. Stock hasanother method not related to Printable.

Page 6: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 6/21

Reference Variables and Interfaces

 An interface is like a class where the internal structure and some of the

 behavior is hidden.

  Interfaces are listed like classes in the API documentation.

  They compile to a .class file, and get loaded by the same process that

loads true classes.

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  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 prefixfrom code within the class, since implementing the interface makes

them part of this class.

To access an interface-implementing class with an interface class reference:

1 [modifiers] InterfaceName variableName; 

Example:

 Both Person and Stock implement Printable.

  Therefore, we can create a reference variable to a Printable, and assign

either aPerson or a Stock object to it.

   We can then call the printAll() method from the Printable reference

 variable, since the compiler knows that method will exist, no matter

 which type of object is actually stored in the variable.

Page 7: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 7/21

1

2

3

4

Person p = new Person(); Stock s = new Stock(); Printable pr; pr = p; 

or

1 pr = s; 

or

1 pr = new Person(); 

Calling an Interface Method

If you have a variable that is declared as a reference to the interface type, you

can use it to call an interface method.

  Note that you cannot call any of the additional methods that are not

defined by the interface.

Code Sample:

Java-Interfaces/Demos/PrintableTest.java1

2

3

45

6

78

9

1011

12

13

14

15

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(); 

} } 

Once pr has been assigned a Printable instance, we can call pr.printAll(); 

   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.

Page 8: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 8/21

Note: to compile this, use *.java; since the name of the file

containing Stock andPerson 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 interfacereference, and typecast it back to that type.

  for instance, to use the sell() method for a Stock:

1 if (pr instanceof Stock) ((Stock) pr).sell(); 

Interfaces and Inheritance

If a class implements an interface, then all subclasses of it will also

automatically implement the interface.

  They are guaranteed to have the necessary methods available.

  It is a good practice to specify that the derived class implements the

interface, just for self-documentation of the code (also for purposes

of javadoc, if the base class is not in the same group of files).

 An interface definition can inherit from another interface.

  The new interface then adds fields 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.

   An interface can actually extend multiple base interfaces, in which case

the combination of all the methods will be required for any

implementing class.

Page 9: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 9/21

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):

Code Sample:Java-Interfaces/Demos/Printable2.java1

23

4

import java.io.PrintStream; public interface Printable2 extends Printable { 

public void printAll(PrintStream p); } 

 A class implementing Printable2 must define both versions of printAll.

Code Sample:

Java-Interfaces/Demos/Printable2Test.java1

2

3

45

6

78

9

101112

13

1415

16

17

import java.io.PrintStream; class Cat implements Printable2 { public void printAll() { 

printAll(System.out); } public void printAll(PrintStream out) { 

out.println("Meow"); } 

public class Printable2Test { public static void main(String[] args) { 

Printable2 c = new Cat(); c.printAll(System.err); c.printAll(); 

} } 

Solution:

Solutions/Payroll-Interfaces01/Payroll.javaThe last several lines of code create an array of invoices, then use

the CheckPrinter to print employees and invoices separately. It would also be

possible to create an array of Payable objects, and add in the elements from both

the employees and invoices arrays, but that seems like an unneccessary

complication for this application.

Page 10: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 10/21

Some Uses for Interfaces

Interfaces and Event-Handling

 A real-world use of interfaces is for event-handling

   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.

 Assuming that there is an event type called XXXEvent:

  The handler interface would probably be named XXXListener.

  The method to register a listener would usually be called addXXXListener.

  The method generating the event probably has a protected utility method

calledfireXXXEvent that it uses to trigger the event notifications (and it is

available for you to call if you extend the class).

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).

1public interface ActionListener { 

public void actionPerformed(ActionEvent e); 

Page 11: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 11/21

Page 12: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 12/21

  It uses a Model-View-Controller approach to separate these sections of

logic into individual classes.

  The TableModel interface defines a set of methods that allow a JTable (the

controller) to query a data model to find out information in order todisplay it.

  The interface forms a framework for a discussion that will take place

 between the controller and the model (like, "How many rows do you

have?" and, "How many columns?", followed by "What's the value at

column 0, row 0?", etc.).

Below are some of the methods from TableModel:

public interface TableModel 

int getColumnCount() Returns the number of columns in the model.int getRowCount() Returns the number of rows in the model.

String getColumnName(int columnIndex ) 

Returns the name of the column at columnIndex.

Class<?> getColumnClass(int columnIndex ) 

Returns the most specific superclass for all the cell values in the column.

Object getValueAt(int rowIndex , int columnIndex ) 

Returns the value for the cell at columnIndex and rowIndex.

boolean isCellEditable(int rowIndex , int columnIndex ) 

Returns true if the cell at rowIndex and columnIndex is editable.

void setValueAt(Object aValue, int rowIndex , int columnIndex ) Sets the value in the cell at columnIndex and rowIndex to aValue.

 You can see the conversation that will take place between the controller and

the model. Note that:

  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 determinefrom 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.

Page 13: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 13/21

  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 usingsetValueAt

.

Code Sample:

Java-Interfaces/Demos/TableModelExample.java1

2

345

6

78

9

1011

12

1314

15

16

17

1819

2021

22

23

2425

26

27

28

2930

3132

33

3435

36

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; 

public class TableModelExample { 

public static void main(String[] args) { 

DemoTableModel model = new DemoTableModel(); 

new TableGUI("Table Model Example", model).setVisible(true); new TableConsole(model); new TableHTML(model); 

} } 

class DemoTableModel extends AbstractTableModel { 

String[] titles = { "Name", "Active", "Grade" }; String[] names = { "Mary", "Joe", "Sue" }; Boolean[] actives = { new Boolean(true), new Boolean(false), 

new Boolean(true) }; Integer[] grades = { new Integer(99), new Integer(87), 

new Integer(89) }; public int getRowCount() { return names.length; } 

public int getColumnCount() { return 3; } 

public String getColumnName(int col) { return titles[col]; 

public Object getValueAt(int row, int column) { if (column == 0) return names[row]; else if (column == 1) return actives[row]; else return grades[row]; 

public void setValueAt(Object v, int row, int column) {} 

Page 14: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 14/21

37

38

39

4041

424344

45

4647

48

49

5051

52

5354

55

56

5758

59

6061

62

63

6465

66

6768

69

7071

72

73

7475

76

77

7879

80

8182

public Class getColumnClass(int column) { if (column == 0) return String.class; else if (column == 1) return Boolean.class; else return Integer.class; 

public boolean isCellEditable(int row, int column) { return false; 

} } 

class TableGUI extends JFrame { 

public TableGUI(String title, DemoTableModel model) { super(title); JTable jt; this.setDefaultCloseOperation(EXIT_ON_CLOSE);  jt = new JTable(model); 

setSize(600,170); getContentPane().add(jt); } 

class TableConsole { 

TableModel model; 

public TableConsole(TableModel model) { 

int rows = model.getRowCount(); int cols = model.getColumnCount(); 

for (int c = 0; c < cols; c++) { System.out.print(fixedStringLength(model.getColumnName(c), 15)); 

} System.out.println(); System.out.println("-------------- -------------- -------------- "); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { 

System.out.print( fixedStringLength(model.getValueAt(r, c).toString(), 15)); 

} System.out.println(); 

} private String fixedStringLength(String in, int size) { if (in.length() > size) in = in.substring(0, 15); char[] blankArray = new char[size - in.length()]; for (int i = 0; i < blankArray.length; i++) blankArray[i] = ' '; return in + String.valueOf(blankArray); 

} } 

class TableHTML { 

Page 15: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 15/21

83

84

85

8687

888990

91

9293

94

95

9697

98

99100

101

102

103104

105

106107

108

109

110111

112

113114

115

116117

118

119

120

TableModel model; 

public TableHTML(TableModel model) { java.io.PrintStream out = System.out; int rows = model.getRowCount(); 

int cols = model.getColumnCount(); out.println("<html><Head><title>My Table</title></head>"); out.println( "<body><table border='1' cellpadding='8' cellspacing='0'><tr>"); 

for (int c = 0; c < cols; c++) { out.print("<th>" + model.getColumnName(c) + "</th>"); 

} out.println("</tr>"); for (int r = 0; r < rows; r++) { out.println("<tr>"); for (int c = 0; c < cols; c++) { 

System.out.print("<td>" + model.getValueAt(r, c) + "</td>"); } out.println("</tr>"); 

} out.println("</table></body></html>");  

} } 

For convenience, all the classes are in one file.

The DemoTableModel  class implements TableModel by extending AbstractTableModel ,

thus gaining implementations of several methods (like those relating to model

change event listener lists), then adding the remaining methods.

Page 16: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 16/21

The model is based on parallel arrays of student data: name, grade, and active

or not- each array represents one column of data, and element 0 in each array

is the same student.

The titles array holds column names.

getColumnCount returns 3, because we know that in advance.

getRowCount returns the length of one of the data arrays.

For getColumnName, we return an appropriate string from the titles array.

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 intablemodel.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.

Page 17: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 17/21

Page 18: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 18/21

Page 19: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 19/21

o  @Override is an example of the source type, since it is only needed

 by the compiler

o   A runtime type that you might encounter the effect of

is@Deprecated

, which states that an element is deprecated - you willreceive a compiler warning if your code uses an element marked

 with this annotation (and, since you might be accessing the

element in an already-compiled class, this annotation must persist

into the compiled class file).

o  @SuppressWarnings is another source annotation, with an

optional element to specify what types of warnings are to be

suppressed.

  The annotation definitions are themselves annotated: -@Target and @Retentionare used before the annotation definition to specify

 which type of element receives the annotation, and what the retention is.

Using Annotations

To apply an annotation to a class or element, precede the item with the name

of the annotation, prefixed with the @ symbol.

If the annotation takes parameters, supply them in parentheses, as a comma

separated list of parameterName=parameterValue . If the only parameter is called

 value, then you can just supply the parameterValue, without specifying it by

name.

1 @AnnotationName(value=parameterValue, parameter2Name=parameter2Value, ...) 

Code Sample:

Java-Interfaces/Demos/AnnotatedWebService.java12

3

4

import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import java.util.Date; 

Page 20: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 20/21

5

6

7

89

101112

13

1415

16

17

1819

20

@WebService(serviceName="DateTimeService")  public class AnnotatedWebService { 

@WebMethod public Date getDate() { 

return new Date(); 

@WebMethod public Date getFutureDate(@WebParam(name="days") int daysOffset) { 

Date d = new Date(); d.setDate(d.getDate() + daysOffset); return d; 

} } 

The @WebService annotation persists into compiled code. Tools that work withenterprise-level web servers (like Glassfish, JBoss, etc.), can read the

annotation via reflection, and install the class as a web service, performing all

the necessary tasks, such as creating a WSDL file, establishing a URL for the

service, and installation it under that URL. The annotation can be

parameterized with the name for the service (which defaults to the class name

followed by "Service"), as well as several other items affecting the setup as a

 web service.

  The serviceName parameter to the @WebService annotation tells the server to

set up the service under that name, as opposed to the default, which

 would have beenAnnotatedWebServiceService  (the default behavior appends

"Service" to the class name, which, in this case, would be redundant).

  The @WebMethod annotations tell the server that these methods should be

set up as RPC methods which can be remotely invoked (by default, the

methods are exposed, the annotation is actually only needed when

renaming the method, or to exclude the method from the service, but

common practice is to include the unparameterized annotation for

methods to be exposed as is).

  The @WebParam annotation is used to rename the daysOffset parameter,

 which would be used from ordinary Java code, to days when the RPC is

Page 21: Nter Faces

8/12/2019 Nter Faces

http://slidepdf.com/reader/full/nter-faces 21/21

remotely invoked. Due to the limitations of reflection, where parameter

names are not preserved into compiled classes, this annotation is

necessary to avoid having the parameters be called arg0, arg1, etc.