Interfaces solve some of the same problems that multiple inheritance does without as much overhead at runtime. However, because interfaces involve dynamic method binding, there is a small performance penalty to using them.
Using interfaces allows several classes to share a programming interface without having to be fully aware of each other's implementation. The following example shows an interface declaration (with the interface keyword) and a class that implements the interface:
public interface Storing { void freezeDry(Stream s); void reconstitute(Stream s); } public class Image implements Storing, Painting { ... void freezeDry(Stream s) { // JPEG compress image before storing ... } void reconstitute (Stream s) { // JPEG decompress image before reading ... } }Like classes, interfaces are either private (the default) or public. The scope of public and private interfaces is the same as that of public and private classes, respectively. Methods in an interface are always public. Variables are public, static, and final.
The following pseudocode illustrates the interfaceName variableName syntax:
class StorageManager { Stream stream; ... // Storing is the interface name void pickle(Storing obj) { obj.freezeDry(stream); } }
returnType methodName ( parameterList );The declaration contains no modifiers. All methods specified in an interface are public and abstract and no other modifiers may be applied.
See Abstract Methods for more information on abstract methods.
interface DoesItAll extends Storing, Painting { void doesSomethingElse(); }
The Java Language Specification
Generated with CERN WebMaker