Implementing Interfaces
Interfaces can be used in type hierarchy just like abstract classes. However, the syntax is slightly different: a class implements an interface whereas it extends another (regular or abstract) class.
For example, here MoocRoster
implements the Roster
interface:
public class MoocRoster implements Roster {
private Student[] students;
private int numStudents;
public MoocRoster(int size) {
students = new Student[size];
numStudents = 0;
}
@Override
public void add(Student s) {
// Implementation omitted to save space
}
@Override
public void remove(Student s) {
// Implementation omitted to save space
}
@Override
public Student find(String email) {
// Implementation omitted to save space
}
}
Notice:
-
The use of keyword
implements
(instead ofextends
). -
MoocRoster
declares its fields (since theRoster
interface does not include fields) and initializes them in its constructor (nosuper
keyword).