Interfaccia Java (con esempi)

In questo tutorial impareremo a conoscere le interfacce Java. Impareremo come implementare le interfacce e quando usarle in dettaglio con l'aiuto di esempi.

Un'interfaccia è una classe completamente astratta che include un gruppo di metodi senza un corpo.

In Java, un'interfaccia definisce un insieme di specifiche che altre classi devono implementare. Per esempio,

 interface Language ( public void getName(); )

Qui abbiamo utilizzato la interfaceparola chiave per creare un'interfaccia denominata Language. L'interfaccia del linguaggio definisce una specifica getName().

Ora, ogni classe che utilizza questa interfaccia dovrebbe implementare la getName()specifica.

Esempio: interfaccia Java

 // create an interface interface Language ( void getName(String name); ) // class implements interface class ProgrammingLanguage implements Language ( // implementation of abstract method public void getName(String name) ( System.out.println("Programming Language: " + name); ) ) class Main ( public static void main(String() args) ( ProgrammingLanguage language = new ProgrammingLanguage(); language.getName("Java"); ) )

Produzione

 Linguaggio di programmazione: Java

Nell'esempio precedente, abbiamo creato un'interfaccia denominata Language. L'interfaccia include un metodo astratto getName().

Qui, la classe ProgrammingLanguage implementa l'interfaccia e fornisce l'implementazione per il metodo.

Non è obbligatorio utilizzare la abstractparola chiave durante la dichiarazione di metodi astratti all'interno di un'interfaccia. È perché un'interfaccia include solo metodi astratti non metodi regolari.

Nota : tutti i metodi all'interno di un'interfaccia sono implicitamente publice tutti i campi lo sono public static final. Per esempio,

 interface Language ( // by default public static final String type = "programming language"; // by default public void getName(); )

Implementazione di un'interfaccia

Come le classi astratte, non possiamo creare oggetti di un'interfaccia. Tuttavia, possiamo implementare un'interfaccia.

Usiamo la implementsparola chiave per implementare un'interfaccia. Per esempio,

 // create an interface interface Polygon ( void getArea(int length, int breadth); ) // implement the Polygon interface class Rectangle implements Polygon ( // implementation of abstract method public void getArea(int length, int breadth) ( System.out.println("The area of the rectangle is " + (length * breadth)); ) ) class Main ( public static void main(String() args) ( // create an object Rectangle r1 = new Rectangle(); r1.getArea(5, 6); ) )

Produzione

 L'area del rettangolo è 30

Nell'esempio precedente, abbiamo creato un'interfaccia denominata Polygon. L'interfaccia contiene un metodo astratto getArea().

Qui, la classe Rectangle implementa Polygon. E fornisce l'implementazione del getArea()metodo.

Nota : una classe può implementare più interfacce. Per esempio,

 interface A ( // members of A ) interface B ( // members of B ) class C implements A, B ( // abstract members of A // abstract members of B )

Estensione di un'interfaccia

Analogamente alle classi, le interfacce possono estendere altre interfacce. La extendsparola chiave viene utilizzata per estendere le interfacce. Per esempio,

 interface Line ( // members of Line interface ) // extending interface interface Polygon extends Line ( // members of Polygon interface // members of Line interface )

Qui, l'interfaccia Polygon estende l'interfaccia Line. Ora, se una qualsiasi classe implementa Polygon, dovrebbe fornire implementazioni per tutti i metodi astratti di Line e Polygon.

Nota : un'interfaccia può estendere più interfacce. Per esempio,

 interface A (… ) interface B (… ) interface C extends A, B (… )

Vantaggi dell'interfaccia in Java

Ora che sappiamo cosa sono le interfacce, impariamo il motivo per cui le interfacce vengono utilizzate in Java.

  • Le interfacce forniscono le specifiche che una classe (che la implementa) deve seguire.
    Nel nostro esempio precedente, abbiamo usato getArea()come specifica all'interno dell'interfaccia Polygon. È come impostare una regola per cui dovremmo essere in grado di ottenere l'area di ogni poligono.
    Ora qualsiasi classe che implementa l'interfaccia Polygon deve fornire un'implementazione per il getArea()metodo.
  • Simili alle classi astratte, le interfacce ci aiutano a ottenere l' astrazione in Java .
    Qui sappiamo che getArea()calcola l'area dei poligoni, ma il modo in cui viene calcolata l'area è diverso per i diversi poligoni. Quindi, l'attuazione di getArea()è indipendente l'una dall'altra.
  • Le interfacce vengono utilizzate anche per ottenere l'ereditarietà multipla in Java. Per esempio,
     interface Line (… ) interface Polygon (… ) class Rectangle implements Line, Polygon (… )

    Qui, la classe Rectangle implementa due diverse interfacce. È così che otteniamo l'ereditarietà multipla in Java.

metodi predefiniti in Java Interfaces

Con il rilascio di Java 8, ora possiamo aggiungere metodi con implementazione all'interno di un'interfaccia. Questi metodi sono chiamati metodi predefiniti.

Per dichiarare i metodi predefiniti all'interno delle interfacce, usiamo la defaultparola chiave. Per esempio,

 public default void getSides() ( // body of getSides() )

Perché metodi predefiniti?

Let's take a scenario to understand why default methods are introduced in Java.

Suppose, we need to add a new method in an interface.

We can add the method in our interface easily without implementation. However, that's not the end of the story. All our classes that implement that interface must provide an implementation for the method.

If a large number of classes were implementing this interface, we need to track all these classes and make changes in them. This is not only tedious but error-prone as well.

To resolve this, Java introduced default methods. Default methods are inherited like ordinary methods.

Let's take an example to have a better understanding of default methods.

Example: Default Method in Java Interface

 interface Polygon ( void getArea(); // default method default void getSides() ( System.out.println("I can get sides of a polygon."); ) ) // implements the interface class Rectangle implements Polygon ( public void getArea() ( int length = 6; int breadth = 5; int area = length * breadth; System.out.println("The area of the rectangle is " + area); ) // overrides the getSides() public void getSides() ( System.out.println("I have 4 sides."); ) ) // implements the interface class Square implements Polygon ( public void getArea() ( int length = 5; int area = length * length; System.out.println("The area of the square is " + area); ) ) class Main ( public static void main(String() args) ( // create an object of Rectangle Rectangle r1 = new Rectangle(); r1.getArea(); r1.getSides(); // create an object of Square Square s1 = new Square(); s1.getArea(); s1.getSides(); ) )

Output

 The area of the rectangle is 30 I have 4 sides. The area of the square is 25 I can get sides of a polygon.

In the above example, we have created an interface named Polygon. It has a default method getSides() and an abstract method getArea().

Here, we have created two classes Rectangle and Square that implement Polygon.

The Rectangle class provides the implementation of the getArea() method and overrides the getSides() method. However, the Square class only provides the implementation of the getArea() method.

Now, while calling the getSides() method using the Rectangle object, the overridden method is called. However, in the case of the Square object, the default method is called.

private and static Methods in Interface

The Java 8 also added another feature to include static methods inside an interface.

Similar to a class, we can access static methods of an interface using its references. For example,

 // create an interface interface Polygon ( staticMethod()(… ) ) // access static method Polygon.staticMethod();

Note: With the release of Java 9, private methods are also supported in interfaces.

We cannot create objects of an interface. Hence, private methods are used as helper methods that provide support to other methods in interfaces.

Practical Example of Interface

Let's see a more practical example of Java Interface.

 // To use the sqrt function import java.lang.Math; interface Polygon ( void getArea(); // calculate the perimeter of a Polygon default void getPerimeter(int… sides) ( int perimeter = 0; for (int side: sides) ( perimeter += side; ) System.out.println("Perimeter: " + perimeter); ) ) class Triangle implements Polygon ( private int a, b, c; private double s, area; // initializing sides of a triangle Triangle(int a, int b, int c) ( this.a = a; this.b = b; this.c = c; s = 0; ) // calculate the area of a triangle public void getArea() ( s = (double) (a + b + c)/2; area = Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println("Area: " + area); ) ) class Main ( public static void main(String() args) ( Triangle t1 = new Triangle(2, 3, 4); // calls the method of the Triangle class t1.getArea(); // calls the method of Polygon t1.getPerimeter(2, 3, 4); ) )

Output

 Area: 2.9047375096555625 Perimeter: 9

In the above program, we have created an interface named Polygon. It includes a default method getPerimeter() and an abstract method getArea().

We can calculate the perimeter of all polygons in the same manner so we implemented the body of getPerimeter() in Polygon.

Now, all polygons that implement Polygon can use getPerimeter() to calculate perimeter.

Tuttavia, la regola per il calcolo dell'area è diversa per i diversi poligoni. Quindi, getArea()è incluso senza implementazione.

Qualsiasi classe che implementa Polygon deve fornire un'implementazione di getArea().

Articoli interessanti...