Lesson 9: Interfaces

Overview

Each Interface introduces a type of the same name as the Interface. An object which implements the interface can be widened to the type of the Interface. An Interface declaraion can contain abstract methods and static final fields. An object implementing the interface must provide bodies for the abstract methods and inherits the static final fields. An interfaces can extend another interface.

Examples

The details

All interfaces are implicitly marked abstract, their methods are all implicitly marked abstract, and their fields are all implicitly marked static and final. When one interface extends another, fields of the same name shadow. Overriding methods must agree in return type.

A class implements an interface by providing bodies for all of the method's own and inherited abstract methods. The class implementing an interface has access to the static final fields. This is the way you import a package of constants into a class. If a class implements two or more interfaces containing fields of the same name, the ambiguous reference must be resolved by casting. Methods of the same name, however, cause no problem, since there are no bodies inherited to cause actual conflict. One implementation overrides them all.

Interfaces provide for certain aspects of multiple inheritance in Java. Two classes which implement an interface can be used interchangably in the context of calling methods from the interface. The compiler will allow you to widen the reference of a class B implementing interface A to a variable of type A, forgetting about the B'ness of the reference.