i Interfaces
Sage-Code Laboratory
index<--

Interfaces

In the Java programming language, an interface is a reference type, similar to a class, that can contain constants, method signatures, default methods, static methods, and constants. Only the default methods and static methods can be implemented in the interface body.

An interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends. On the other hand a class can implement multiple interfaces. This is the term. A class can not extend interface but implements them.

Rules:

Interface

Interface Hierarchy

Syntax:

An interface declaration consists of modifiers, the keyword interface.

//simple interfaces
public interface Interface1 { ... };
public interface Interface2 { ... };
public interface Interface3 { ... };

//define a group of interfaces
public interface GroupInterface extends Interface1, Interface2, Interface3 {
    // constant declarations
    ....
    // abstract methods
    ....
    // default methods
    ....
    // static methods
    ....
};

Notes:

Interface Implementation

Interfaces can not be used until they are implemented. A class can implements one or more interfaces. We specify what interfaces are implemented in the class declaration statement.

Syntax:

Next is a syntax pattern for implementing a class with 3 interfaces:


public class GroupClass implements Interface1, Interface2, Interface3 {
    // fields
    ....
    // methods
    ....
}

Rules:

Using Interfaces

We can define an object of type interface. That's the point to have interfaces. An interface is a data type, so we can declare objects that satisfy the requirements of an interface. Once defined we can set value for it an object that is descendent of a class that implements that particular interface.

Syntax:

In next pseudo-code fragment we define a method that internally uses interfaces as types.

 //create dummy interfaces
public interface Interface1 {
   aMethod()
};

public interface Interface2 {
   bMethod()
};

....
// define a method that uses interface objects
public void callMethods(Object obj1, Object obj2) {
    //cast parameter objects to interfaces
    Interface1 object1 = (Interface1) obj1;
    Interface2 object2 = (Interface2) obj2;

    //call methods from interfaces
    object1.aMethod(); //call a method from interface 1
    object2.bMethod(); //call a method from interface 2
}

Read Next: Lambda Expressions