Section 10.3 Java Interfaces
We will return to some of the more general discussions shortly, but it is time to introduce our protagonists for this section of the book, namely Java interfaces.
A Java Interface is a group of zero or more method signatures without any implementation for these methods. Java classes are said to implement an interface when they contain implementations for all the methods described in the interface.A variable can be declared to have an interface as its type, and in that case it can only hold as its value objects of classes that implement that interface.
So in a certain sense a Java interface is simply the formal way of specifying what we described as an interface earlier. As a simple example, I could create a
Grade
interface:interface Grade {
String getLetter();
double getPoints();
boolean countsForCredit();
}
This little block of code tells me that if I have a variable
g
whose type is Grade
, then I can call g.getLetter()
and get back a string, I can call g.getPoints()
and get back a double, etc.How do I obtain an object of type
Grade
? We cannot use the new
keyword with a interface in order to create an object, there is no constructor (I am lying a little here, there is a way to do it but it’s not used often). What we need is a class that implements that interface:A classA
implements an interfaceI
when:
It states that it implements it in its definition It provides implementations for all the methods stated in the interface
So for example we can create a
SimpleGrade
class that implements the Grade
interface as follows:class SimpleGrade implements Grade {
SimpleGrade(letter) {
this.letter = letter;
}
public String getLetter() { return letter; }
public double getPoints() { return .. compute points for letter ..; }
public boolean countsForCredit() { return .. determine if letter counts..; }
...
}
A couple of things to note here:
- We can have other methods in the class beyond those specified by the interface.
- The methods specified by the interface are automatically considered public. Therefore the corresponding methods in the class must also be declared public.
Armed with this class, we can now write code like this:
Grade g = new SimpleGrade("A");
g.getPoints(); // hopefully 4.00
We declare a variable of type
Grade
and assign to it as value a new object of class SimpleGrade
. The compiler knows that this is OK because the SimpleGrade
class is promising to implement the Grade
interface, and the compiler already checked that.So why does this matter, what’s the advantage of using the
Grade
interface over the SimpleGrade
class? Let’s discuss this next.