Creating and Extending Interfaces
New Interfaces
To create a new interface,we declare it like this:
public interface Growable
{
…
}
This is, effectively, the same as a class definition, with the word interface replacing the word class. Inside the interface definition we have methods and constants.
The method definitions inside the interface are public and abstract methods; We cannot declare a method inside an interface to be either private or protected.
So, for example, here’s a Growable interface with one method explicitly declared public and abstract (growIt()) and one implicitly declared as such (growItBigger())
public interface Growable
{
public abstract void growIt(); //explicity public and abstract
void growItBigger(); // effectively public and abstract
}
In addition to methods, interfaces can also have variables, but those variables must be declared public, static, and final (making them constant).
As with methods, we can explicitly define a variable to be public, static, and final.
Here’s that same Growable definition with two new variables:
public interface Growable
{
public static final int increment = 10;
long maxnum = 1000000; // becomes public static and final
public abstract void growIt(); //explicitly public and abstract
void growItBigger(); // effectively public and abstract
}
Interfaces, like classes, can belong to a package by adding a package statement to the first line of the class file.
Interfaces can also import other interfaces and classes from other packages, just as classes can.