Download Interface

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Object-Oriented
Programming:
Interface
 2005 Pearson Education, Inc. All rights reserved.
2
10.7.1 Developing a Payable Hierarchy
• An interface is a group of related methods with empty
bodies, and might also contain constant definitions.
• Interfaces form a contract between the class and the
outside world.
• an interface can extend any number of interfaces.
• UML representation of interfaces
– Interfaces are distinguished from classes by placing the
word “interface” (« and ») above the interface name
– The relationship between a class and an interface is known
as realization
• A class “realizes” the method of an interface
 2005 Pearson Education, Inc. All rights reserved.
3
Good Programming Practice 10.2
Interface’s method name is better to describe the
method’s purpose in a general manner,
because the method may be implemented by a broad
range of unrelated classes.
 2005 Pearson Education, Inc. All rights reserved.
4
Payable interface Contains method getPaymentAmount Is implemented by the
Invoice and Employee classes
Fig. 10.10 | Payable interface hierarchy UML class diagram.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 10.11: Payable.java
2
// Payable interface declaration.
4
public interface Payable
5
{
7
Outline
Declare interface Payable
3
6
5
double getPaymentAmount(); // calculate payment; no implementation
Payable.java
} // end interface Payable
Declare getPaymentAmount method which is
implicitly public and abstract
• An interface can contain constant declarations in addition to method declarations.
• All constant values defined in an interface are implicitly public, static, and final.
 2005 Pearson Education,
Inc. All rights reserved.
1
2
// Fig. 10.12: Invoice.java
// Invoice class implements Payable.
6
Outline
3
4
public class Invoice implements Payable
5
6
{
private String partNumber;
Class Invoice implements
interface Payable
7
8
private String partDescription;
private int quantity;
9
10
private double pricePerItem;
11
12
// four-argument constructor
public Invoice( String part, String description, int count,
13
14
15
16
Invoice.java
(1 of 3)
double price )
{
partNumber = part;
partDescription = description;
setQuantity( count ); // validate and store quantity
17
18
19
20
setPricePerItem( price ); // validate and store price per item
} // end four-argument Invoice constructor
21
// set part number
22
public void setPartNumber( String part )
23
24
{
25
26
} // end method setPartNumber
partNumber = part;
 2005 Pearson Education,
Inc. All rights reserved.
27
28
// get part number
public String getPartNumber()
29
{
30
31
return partNumber;
} // end method getPartNumber
32
33
34
35
36
// set description
public void setPartDescription( String description )
{
partDescription = description;
37
38
39
40
41
42
} // end method setPartDescription
43
44
45
46
47
48
49
} // end method getPartDescription
50
51
52
53
54
55
56
7
Outline
Invoice.java
(2 of 3)
// get description
public String getPartDescription()
{
return partDescription;
// set quantity
public void setQuantity( int count )
{
quantity = ( count < 0 ) ? 0 : count; // quantity cannot be negative
} // end method setQuantity
// get quantity
public int getQuantity()
{
return quantity;
} // end method getQuantity
 2005 Pearson Education,
Inc. All rights reserved.
57
58
// set price per item
public void setPricePerItem( double price )
59
60
61
{
8
Outline
pricePerItem = ( price < 0.0 ) ? 0.0 : price; // validate price
} // end method setPricePerItem
62
63
64
65
// get price per item
public double getPricePerItem()
{
66
67
return pricePerItem;
} // end method getPricePerItem
Invoice.java
(3 of 3)
68
69
70
// return String representation of Invoice object
public String toString()
71
72
{
return String.format( "%s: \n%s: %s (%s) \n%s: %d \n%s: $%,.2f",
"invoice", "part number", getPartNumber(), getPartDescription(),
73
74
75
76
77
78
"quantity", getQuantity(), "price per item", getPricePerItem() );
} // end method toString
79
{
// method required to carry out contract with interface Payable
public double getPaymentAmount()
80
return getQuantity() * getPricePerItem(); // calculate total cost
81
} // end method getPaymentAmount
Declare getPaymentAmount
82 } // end class Invoice
to fulfill
contract with interface Payable
 2005 Pearson Education,
Inc. All rights reserved.
9
10.7.3 Creating Class Invoice
• A class can implement as many interfaces as it
needs
– Use a comma-separated list of interface names after
keyword implements
• Example: public class ClassName extends
SuperclassName implements FirstInterface,
SecondInterface, …
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 10.13: Employee.java
2
// Employee abstract superclass implements Payable.
10
Outline
3
4
public abstract class Employee implements Payable
5
{
6
private String firstName;
7
private String lastName;
8
private String socialSecurityNumber;
Class Employee implements
interface Payable
9
10
// three-argument constructor
11
public Employee( String first, String last, String ssn )
12
{
13
firstName = first;
14
lastName = last;
15
socialSecurityNumber = ssn;
16
Employee.java
(1 of 3)
} // end three-argument Employee constructor
17
 2005 Pearson Education,
Inc. All rights reserved.
18
19
// set first name
public void setFirstName( String first )
20
21
22
{
11
Outline
firstName = first;
} // end method setFirstName
23
24
25
26
27
// return first name
public String getFirstName()
{
return firstName;
28
29
} // end method getFirstName
30
31
// set last name
public void setLastName( String last )
32
33
34
35
{
36
37
38
39
// return last name
public String getLastName()
{
return lastName;
40
41
} // end method getLastName
Employee.java
(2 of 3)
lastName = last;
} // end method setLastName
 2005 Pearson Education,
Inc. All rights reserved.
42
43
// set social security number
public void setSocialSecurityNumber( String ssn )
44
45
{
46
47
48
49
50
51
52
53
} // end method setSocialSecurityNumber
54
55
// return String representation of Employee object
public String toString()
56
57
58
59
60
61
{
62
// this class must be declared abstract to avoid a compilation error.
12
Outline
socialSecurityNumber = ssn; // should validate
Employee.java
// return social security number
public String getSocialSecurityNumber()
{
return socialSecurityNumber;
} // end method getSocialSecurityNumber
(3 of 3)
return String.format( "%s %s\nsocial security number: %s",
getFirstName(), getLastName(), getSocialSecurityNumber() );
} // end method toString
// Note: We do not implement Payable method getPaymentAmount here so
63 } // end abstract class Employee
getPaymentAmount method is
not implemented here
 2005 Pearson Education,
Inc. All rights reserved.
10.7.5 Modifying Class
SalariedEmployee for Use in the
Payable Hierarchy
13
• Objects of any subclasses of the class that
implements the interface can also be thought of as
objects of the interface
– A reference to a subclass object can be assigned to an
interface variable if the superclass implements that
interface
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 10.14: SalariedEmployee.java
2
// SalariedEmployee class extends Employee, which implements Payable.
3
4
5
public class SalariedEmployee extends Employee
{
14
Class SalariedEmployee extends class Employee
(which implements interface Payable)
6
7
8
private double weeklySalary;
9
10
11
public SalariedEmployee( String first, String last, String ssn,
double salary )
{
// four-argument constructor
super( first, last, ssn ); // pass to Employee constructor
12
13
14
Outline
setWeeklySalary( salary ); // validate and store salary
} // end four-argument SalariedEmployee constructor
SalariedEmployee
.java
(1 of 2)
15
16
17
// set salary
public void setWeeklySalary( double salary )
18
19
20
21
{
weeklySalary = salary < 0.0 ? 0.0 : salary;
} // end method setWeeklySalary
 2005 Pearson Education,
Inc. All rights reserved.
22
// return salary
23
public double getWeeklySalary()
24
{
Outline
return weeklySalary;
25
26
15
} // end method getWeeklySalary
27
28
29
// calculate earnings; implement interface Payable method that was
// abstract in superclass Employee
30
31
public double getPaymentAmount()
{
32
return getWeeklySalary();
33
34
} // end method getPaymentAmount
35
36
// return String representation of SalariedEmployee object
public String toString()
37
{
SalariedEmployee
.java
Declare getPaymentAmount method
instead of earnings method
(2 of 2)
38
return String.format( "salaried employee: %s\n%s: $%,.2f",
39
super.toString(), "weekly salary", getWeeklySalary() );
40
} // end method toString
41 } // end class SalariedEmployee
 2005 Pearson Education,
Inc. All rights reserved.
16
Software Engineering Observation 10.8
• When a method parameter receives a variable of interface type,
any object of a class that implements the interface may be passed
as an argument.
• When a method parameter receives a variable of a superclass
type, any object of a subclass may be passed as an argument.
• If you define a reference variable whose type is an interface, any
object you assign to it must be an instance of a class that
implements the interface.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 10.15: PayableInterfaceTest.java
2
// Tests interface Payable.
17
Outline
3
4
5
6
7
8
public class PayableInterfaceTest
{
Declare array of Payable variables
public static void main( String args[] )
{
// create four-element Payable array
PayableInterface
Test.java
9
10
11
Payable payableObjects[] = new Payable[ 4 ];
12
payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 );
13
14
payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 );
payableObjects[ 2 ] =
15
// populate array with objects that implement Payable
Assigning references to
(1 of 2) objects to
Invoice
Payable variables
new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
16
17
payableObjects[ 3 ] =
new SalariedEmployee( "Lisa", "Barnes", "888-88-8888", 1200.00 );
18
19
20
21
System.out.println(
"Invoices and Employees processed polymorphically:\n" );
Assigning references to
SalariedEmployee
objects to Payable variables
 2005 Pearson Education,
Inc. All rights reserved.
22
// generically process each element in array payableObjects
23
for ( Payable currentPayable : payableObjects )
24
25
{
26
27
28
29
18
Outline
// output currentPayable and its appropriate payment amount
System.out.printf( "%s \n%s: $%,.2f\n\n",
currentPayable.toString(),
"payment due", currentPayable.getPaymentAmount() );
} // end for
30
} // end main
31 } // end class PayableInterfaceTest
Invoices and Employees processed polymorphically:
invoice:
part number: 01234 (seat)
quantity: 2
price per item: $375.00
payment due: $750.00
PayableInterface
Test.java
Call toString and getPaymentAmount
methods polymorphically
(2 of 2)
invoice:
part number: 56789 (tire)
quantity: 4
price per item: $79.95
payment due: $319.80
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
payment due: $800.00
salaried employee: Lisa Barnes
social security number: 888-88-8888
weekly salary: $1,200.00
payment due: $1,200.00
 2005 Pearson Education,
Inc. All rights reserved.
19
10.7.7 Declaring Constants with
Interfaces
• Interfaces can be used to declare related
constants used in many class declarations
– These constants are implicitly public, static and
final
– Using a static import declaration allows clients to use
these constants with just their names
– A static import: class name and a dot (.) are not required to
use an imported static member.
– Format:
• import static packageName.ClassName.staticMemberName;
• import static packageName.ClassName.*;
 2005 Pearson Education, Inc. All rights reserved.
20
Example on static import
import static java.lang.Math.*;
public class StaticImportTest
{
public static void main( String args[] )
{
System.out.printf( "sqrt( 900.0 ) = %.1f\n", sqrt( 900.0 ) );
System.out.printf( "ceil( -9.8 ) = %.1f\n", ceil( -9.8 ) );
} // end main
} // end class StaticImportTes
 2005 Pearson Education, Inc. All rights reserved.
21
Interface
Description
Comparable
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that
allow you to compare primitive values. However, these operators cannot be
used to compare the contents of objects. Interface Comparable is used to
allow objects of a class that implements the interface to be compared to one
another. The interface contains one method, compareTo, that compares the
object that calls the method to the object passed as an argument to the method.
Classes must implement compareTo such that it returns a value indicating
whether the object on which it is invoked is less than (negative integer return
value), equal to (0 return value) or greater than (positive integer return value)
the object passed as an argument, using any criteria specified by the
programmer. For example, if class Employee implements Comparable, its
compareTo method could compare Employee objects by their earnings
amounts. Interface Comparable is commonly used for ordering objects in a
collection such as an array.
Serializable A tagging interface used only to identify classes whose objects can be written
to (i.e., serialized) or read from (i.e., deserialized) some type of storage (e.g.,
file on disk, database field) or transmitted across a network.
 2005 Pearson Education, Inc. All rights reserved.