Java Interfaces
Java has a construct called Interface which is closely related to abstract classes.
In a nutshell, an interface is an abstract class that contains nothing but abstract methods.
You can think of an interface as another level of abstraction that is even more abstract than an abstract class!
Consider the following modified abstract Roster
class where the fields and the constructors are removed.
public abstract class Roster {
public abstract void add(Student s);
public abstract void remove(Student s);
public abstract Student find(String email);
}
The above can be rewritten as follows, which is arguably a more compact and cleaner representation of the Roster ADT.
public interface Roster {
void add(Student s);
void remove(Student s);
Student find(String email);
}
Notice the syntax of Java interface:
-
We declare it with the keyword
interface
(instead ofclass
orabstract class
) -
It does not contain fields nor constructors.
-
Since all methods are public and abstract, there is no need to include those keywords in their declaration.
Aside: In recent versions of Java, an interface can technically contain constants, default methods, static methods, and nested types. In this course however, we use Java's interface as an abstract class that has nothing but abstract methods.
Java interfaces, like abstract classes, can be used to declare objects but not to instantiate them.
Resources
An article on Medium claims to be the Easiest explanation of Abstract class and Interface!