Interfaces
Interfaces
Implement
How to implement an interface
- To declare a class that implements an interface:
- you use the implements keyword
- you provide an implementation for each method defined by the interface
- If you forget to implement an interface method, the compiler will issue an error message.
- A class that implements an interface can use any constant defined by that interface.
The syntax for implementing an interface
public class ClassName
implements Interface1[, Interface2]...{}
A class that implements two interfaces
import java.text.NumberFormat;
public class Employee implements Printable,
DepartmentConstants
{
private int department;
private String firstName;
private String lastName;
private double salary;
public Employee(int department, String lastName,
String firstName, double salary)
{
this.department = department;
this.lastName = lastName;
this.firstName = firstName;
this.salary = salary;
}
public void print()
{
NumberFormat currency =
NumberFormat.getCurrencyInstance();
System.out.println("Name:\t" + firstName + " " + lastName);
System.out.println("Salary:\t" + currency.format(salary));
String dept = "";
if (department == ADMIN)
dept = "Administration";
else if (department == EDITORIAL)
dept = "Editorial";
else if (department == MARKETING)
dept = "Marketing";
System.out.println("Dept:\t" + dept);
}
}