Java Interfaces |
As mentioned
earlier, multiple inheritances is directly not allowed in Java,
however, the same could be achieved through the concept of Interface in Java.
Inheritance implements the "is-a" relationship and an interface
is similar to a class, but can only contain public, static, final fields
(i.e., constants) and public abstract methods (i.e., just method headers,
with no bodies).
An interface is declared as shown below:
An interface is declared as shown below:
public
interface Employee {
void RaiseSalary( double d );
double GetSalary();
}
Note that both methods are
implicitly public and abstract (those keywords can be provided, but are not
necessary in an interface).
A class can implement one or more interfaces (in addition to extending one class). It must provide bodies for all of the methods declared in the interface, or else it must be abstract. For example:
A class can implement one or more interfaces (in addition to extending one class). It must provide bodies for all of the methods declared in the interface, or else it must be abstract. For example:
- public class TA implements Employee {
- void
RaiseSalary( double d ) {
- //
actual code here
- }
-
double GetSalary() {
- //
actual code here
- }
- }
- Public interfaces (like public classes) must
be in a file with the same name. A single class can implement
many interfaces at the same time thus achieving multiple
inheritance.
An interface can also be used as a "marker" with no fields or methods. A marker interface is used only to "mark" a class as having a property, and is testable via theinstanceof operator.