Interfaces. Features of use in combination with classes. The advantages of using interfaces. Keywords interface, implements. Examples

Interfaces. Features of use in combination with classes. The advantages of using interfaces. Keywords interface, implements. Examples


Before studying this topic it is recommended to familiarize yourself with the topic:


Contents



1. What are the interfaces used for? Advantages of using interfaces

Interfaces are used to create completely abstract classes that contain no implementation at all. Interfaces do not contain an implementation. Thus, interfaces are intended to describe what can be implemented by classes that implement these interfaces. In other words, interfaces indicate, which can be implemented, but not how it should be implemented. Interfaces describe the form and not the implementation.

The interface contains the names of the methods, argument lists, and the types of values that are returned, but not the implementations of these methods.

The use of interfaces provides the following interrelated advantages:

  • the interface actually defines the “protocol” of inter-class interaction;
  • combining interfaces and classes allows you to clearly separate the declaration of public methods from their implementation;
  • interfaces isolate the definition of one or more methods from the inheritance hierarchy. As a result, classes that are not hierarchically interconnected can implement the same interface;
  • any method that uses an interface knows only which interface methods will be called and no more. The implementation of methods is carried out in classes that implement this interface and remains hidden;
  • the combination of the possibilities of interfaces and classes is effective in the case of the implementation of various design patterns (patterns);
  • interfaces allow to partially implement the so-called “multiple inheritance”, which was implemented in C++.

 

2. The general form of the interface declaration. The keyword interface

The general form of the interface declaration is as follows:

access_modifier interface Name {
    return_type method_name1(parameters1);
    return_type method_name2(parameters2);

    // ...

    type var_name1 = value1;
    type var_name2 = value2;

    // ...
    return_type method_nameN(parametersN);
    type var_nameN = valueN;
}

here

  • interface – a keyword that specifies that the Java language element being declared is an interface;
  • access_modifier – one of the access modifiers: public or abstract;
  • Name – the interface name;
  • return_type – some type that returns a method named method_name1, method_name2, method_nameN;
  • parameters1, parameters2, parametersN – parameters of methods method_name1, method_name2, method_nameN;
  • type – the type of the variable declared in the interface;
  • var_name1, var_name2, var_nameN – variables names that are declared in the interface. Any variable declared in the interface, is declared with final and static modifiers. This variable must be initialized. In a class that implements an interface, you cannot change the value of a variable.

 

3. What is the general form of interface implementation in the class? Keyword implements

If the interface is defined, then it can be implemented in the class. The general form of implementing an interface in a class is:

class SomeClass implements SomeInterface {
    // implementation of interface methods and other class methods
    // ...
}

here SomeClass – the name of the class that implements the SomeInterface interface.

 

4. What is necessary to perform (implement) in the class that implements the specified interface?

If a class implements an interface, then the following commitments are established for this class:

  • the class must contain the implementation of the methods declared in this interface;
  • the signature of the interface methods must match the signature of the same methods implemented in the class;
  • methods that implement interface elements must be declared as public in a class;
  • in the class it is forbidden to change the values of variables declared in the interface.

 

5. Examples of declaring interfaces and classes that implement them

Example 1. The example demonstrates:

  • declaration of methods in the interface;
  • variable declaration in the interface;
  • interface implementation in the class;
  • use of an interface reference to access methods.

Let an interface named IMathFunctions be declared within the package in the IMathFunctions.java file as shown below

// interface that contains math functions declarations
public interface IMathFunctions {
    double pi=3.1415926535; // variable, number Pi
    int Power(int x, int y); // x to the power of y
    double AbsComplex(double real, double imag); // the module of complex number
}

The interface contains the following declarations:

  • the variable pi, which determines the number of pi. This variable is implicitly declared as final and static. If some class implements this interface, then you cannot change the values of this variable;
  • mathematical function Power(), designed to raise a number to a power;
  • mathematical function AbsComplex(), which returns the module of a complex number.

After the interface is declared, a class is declared that must implement the methods of this interface. In our case, the MathFunctions class is declared.

// class that implements the IMathFuncitons interface
public class MathFunctions implements IMathFunctions {
    // Implementation of IMathFunctions interface methods
    // 1. The module of Complex number
    public double AbsComplex(double real, double imag) {
        double abs;
        abs = Math.sqrt(real*real+imag*imag);
        return abs;
    }

    // 2. x in power y
    public int Power(int x, int y) {
        int p, i;
        p = 1;
        for (i=1; i<=y; i++)
            p=p*x;
        return p;
    }

    // Internal method of class
    // Determination of the circumference
    public double Circumference(double radius) {
        return 2*pi*radius; // use the variable pi from the interface
    }
}

Using an interface in a class may be, for example, the following

// using the interface
IMathFunctions mf = new MathFunctions(); // declare an instance of the class MathFunctions
//IMathFunctions mf2 = new IMathFunctions(); error - forbidden to create an instance of the interface

// invoke the interface methods via mf instance
int d;
double x;
d = mf.Power(3, 4); // d = 81
x = mf.AbsComplex(2, 3); // x = 3.605551275463989
double pi;
pi = mf.pi; // pi = 3.1415926535

In the above code, the mf link to the IMathFunctions interface is first declared. Then for this mf link, an instance of the MathFuncions class is created. This implementation works because the MathFunctions class implements the IMathFunctions interface. Using the mf link, you can invoke the interface methods.

Example 2. The example demonstrates the use of the IStrings interface, which declares string processing methods:

  • method GetNSymbols() that counts the number of characters in a string;
  • method ConvertOdd(), which returns a string consisting of characters lying on odd positions.

The ProcessStrings class implements the IStrings interface.

The interface implementation is placed in the IStrings.java file and looks like this:

public interface IStrings {
    // counts the number of characters in a string
    int GetNSymbols(char c, String s);

    // forms a string consisting of the characters of string s,
    // which are placed on odd positions: 1, 3, 5, ...
    String ConvertOdd(String s);
}

The class implementation is described in the ProcessStrings.java file and has the following form

// class that implements the IStrings interface
public class ProcessStrings implements IStrings {
    // implementation of methods that are declared in the interface
    // calculate the number of characters in the string s, there may be a public method
    public int GetNSymbols(char c, String s) {
        int i;
        int k = 0;
        for (i=0; i<s.length(); i++)
            if (c==s.charAt(i))
                k++;
        return k;
    }

    // forms a string consisting of the characters of string s,
    // which are placed on odd positions: 1, 3, 5, ...
    public String ConvertOdd(String s) {
        String s2="";
        int i;
        for (i=0; i<s.length(); i++) {
            if (i%2==1) // if odd position
                s2=s2+s.charAt(i);
        }
        return s2;
    }

    public static void main(String[] args) {
        // demonstration of the interface IStrings
        IStrings obj = new ProcessStrings();
        String s1 = "bestprog.net";
        String s2;
        int k;

        s2 = obj.ConvertOdd(s1); // s2 = "etrgnt"
        k = obj.GetNSymbols('t', s1); // k = 2
        System.out.println("s2 = " + s2);
        System.out.println("k = " + k);
    }
}

As you can see from the code, in the ProcessStrings class implements the GetNSymbols() and ConvertOdd() methods. The static main() function of the ProcessStrings class is the entry point to the program. As a result of the execution of the main() function, the following result will be output:

s2 = etrgnt
k = 2

 

6. Is it possible to create an instance (object) of the interface?

Since the interface contains only the declaration without implementation, it is prohibited to create an instance of the interface. However, a link to the interface can be announced. But when allocating memory with the operator new, the class constructor that implements this interface must be specified.

 

7. How many classes can the interface be implemented in?

The interface can be implemented in any number of classes. For example, in the following code, two different classes with the names SomeClass1, SomeClass2 implement one interface SomeInterface.

// some interface
interface SomeInterface {
    // ...
    void method1(int d);
    double method2(double x);
}

// class that implements the interface
class SomeClass1 implements SomeInterface {
    // ...
    void method1(int d) {
        // implementation
        // ...
    }

    double method2(double x) {
        // implementation
        // ...
    }
}

// another class that implements the interface
class SomeClass2 implements SomeInterface {
    // ...
    void method1(int d) {
        // implementation
        // ...
    }

    double method2(double x) {
        // implementation
        // ...
    }
}

 

8. How many interfaces can one class implement?

A class can implement any number of interfaces. In this case, interface names are separated by commas. For example, in the following code

class ClassName implements Interface1, Interface2, Interface3 {
    // ...
}

the class named ClassName implements interfaces named Interface1, Interface2, Interface3.

 

9. What type of access must have methods declared in the interface?

Methods declared in the interface must be public, that is, they must be of public access type.

 

10. What the default access type have methods declared in the interface?

If no access type is specified in the method declaration, then these methods have the public access type. For example, in the following code

interface SomeInterface {
    public void method1(int d);
    int method2(int x, int y);
}

both methods method1() and method2() have public access.

 

11. How to invoke class methods using references to interfaces?

The sequence of steps is as follows (see example from p. 5):

  1. Declare a reference to the interface
  2. Allocate memory for reference by specifying the class constructor that implements the interface.
  3. Invoke methods or variables declared in the interface.

For example. Let the interface with the name I and the class with the name C be given. The interface I declares the method

interface I {
    void method();
    int d = 5;
}

class C implements I {
    // ...
    // implementation of method of interface I
    public void method() {
        // ...
    }
}

The use of method() with the interface I may be as follows:

I obj; // 1. Declare a reference
obj = new C(); // 2. Create an instance using the class constructor
obj.method(); // 3. Invoke the interface method
int t = obj.d; // 3. Invoke the interface variable

 

12. Requirements for declaring variables in interfaces

It is possible to declare a variable in the interface. Any variable declared implicitly in the interface is declared with final and static modifiers. This variable must be initialized. In a class that implements an interface, you cannot change the value of a variable.

 

13. In what cases, you can use the public access specifier in interface declaration?

The public access specifier can be used before the interface name only when the interface is defined in a file that has the same name. If the interface name does not match the file name, then the public specifier cannot be used in the interface declaration.

For example. A file named IMyInterface.java is specified. In this file, you can declare a public interface with the same name.

public interface MyInterface {
    // ...
}

 

14. How to add an interface declaration in Java Eclipse?

In systems that support Java programming, the addition of interfaces to a project is implemented using special commands.

To add an interface to a project in a Java Eclipse programming system, follow these steps.

1. Activate the project to which you want to add an interface (Figure 1).

Java Eclipse Activating project

Figure 1. Activating a project named Project15 in Java Eclipse

2. Invoke the command of interface creation

File->New->Interface

Java Eclipse command add interface

Figure 2. The command to add an interface to the project

As a result, the “New Java Interface” window will open (Figure 3).

3. In the “New Java Project” window, the following actions must be performed (see Figure 3):

  • in the field “Source folder:” you need to check the name of the folder with the project. In our case, the folder name with the project is “Project15/src”. Optionally, you can install another folder;
  • in the field “Name:” you need to specify the name of the interface, for example, MyInterface.

Java Eclipse Window "New Java Interface"

Figure 3. Window “New Java Interface”. Set the project name Project15 and MyInterface interface

4. After selecting the Finish button, the interface named MyInterface will be added to the Project 15 project as shown in Figure 4.

Java Eclipse interface Package Explorer window

Figure 4. Displaying the interface in the Package Explorer window and the MyInterface.java window

For the interface, a separate file MyInterface.java is created. Apparently, the interface file name and interface name are the same. Also, the interface is declared as public in order to be accessible from other files, packages.

 


Related topics