Antaramuka Java (Dengan Contoh)

Dalam tutorial ini, kita akan belajar mengenai antara muka Java. Kami akan belajar bagaimana melaksanakan antara muka dan kapan menggunakannya secara terperinci dengan bantuan contoh.

Antaramuka adalah kelas abstrak sepenuhnya yang merangkumi sekumpulan kaedah tanpa badan.

Di Java, antara muka menentukan sekumpulan spesifikasi yang mesti dilaksanakan oleh kelas lain. Sebagai contoh,

 interface Language ( public void getName(); )

Di sini, kami telah menggunakan interfacekata kunci untuk membuat antara muka bernama Bahasa. Antaramuka Bahasa menentukan spesifikasi getName().

Sekarang, setiap kelas yang menggunakan antara muka ini harus melaksanakan getName()spesifikasi.

Contoh: Antaramuka 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"); ) )

Pengeluaran

 Bahasa Pengaturcaraan: Java

Dalam contoh di atas, kami telah membuat antara muka bernama Bahasa. Antara muka merangkumi kaedah abstrak getName().

Di sini, kelas ProgrammingLanguage menerapkan antara muka dan menyediakan pelaksanaan untuk kaedah tersebut.

Tidak wajib menggunakan abstractkata kunci semasa menyatakan kaedah abstrak di antara muka. Ini kerana antara muka hanya merangkumi kaedah abstrak bukan kaedah biasa.

Catatan : Semua kaedah di antara muka tersirat publicdan semua bidang secara tersirat public static final. Sebagai contoh,

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

Melaksanakan Antaramuka

Seperti kelas abstrak, kita tidak dapat membuat objek antara muka. Walau bagaimanapun, kami dapat melaksanakan antara muka.

Kami menggunakan implementskata kunci untuk melaksanakan antara muka. Sebagai contoh,

 // 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); ) )

Pengeluaran

 Luas segi empat tepat ialah 30

Dalam contoh di atas, kami telah membuat antara muka bernama Polygon. Antaramuka mengandungi kaedah abstrak getArea().

Di sini, kelas Rectangle menerapkan Polygon. Dan, menyediakan pelaksanaan getArea()kaedah.

Catatan : Kelas dapat melaksanakan pelbagai antara muka. Sebagai contoh,

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

Memperluaskan Antara Muka

Sama seperti kelas, antara muka dapat memperluas antara muka lain. Kata extendskunci digunakan untuk memperluas antara muka. Sebagai contoh,

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

Di sini, antara muka Polygon memperluas antara muka Line. Sekarang, jika ada kelas yang menerapkan Polygon, ia harus menyediakan implementasi untuk semua kaedah abstrak dari Line dan Polygon.

Catatan : Antaramuka dapat memperluas pelbagai antara muka. Sebagai contoh,

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

Kelebihan Antaramuka di Java

Sekarang kita tahu apa antara muka, mari kita pelajari mengapa antara muka digunakan di Java.

  • Antaramuka memberikan spesifikasi yang mesti diikuti oleh kelas (yang menerapkannya).
    Dalam contoh sebelumnya, kami telah menggunakan getArea()spesifikasi di dalam poligon antara muka. Ini seperti menetapkan peraturan bahawa, kita seharusnya dapat mendapatkan luas setiap poligon.
    Sekarang mana-mana kelas yang melaksanakan antara muka Polygon mesti menyediakan pelaksanaan getArea()kaedah tersebut.
  • Sama seperti kelas abstrak, antara muka membantu kita mencapai pengabstrakan di Jawa .
    Di sini, kita tahu getArea()mengira luas poligon tetapi cara luas dikira berbeza untuk poligon yang berbeza. Oleh itu, pelaksanaan getArea()adalah bebas antara satu sama lain.
  • Antaramuka juga digunakan untuk mencapai pelbagai warisan di Jawa. Sebagai contoh,
     interface Line (… ) interface Polygon (… ) class Rectangle implements Line, Polygon (… )

    Di sini, Rectangle kelas melaksanakan dua antara muka yang berbeza. Ini adalah bagaimana kita memperoleh banyak warisan di Jawa.

kaedah lalai dalam Java Interfaces

Dengan pembebasan Java 8, kita sekarang dapat menambahkan metode dengan implementasi di dalam antarmuka. Kaedah ini dipanggil kaedah lalai.

Untuk menyatakan kaedah lalai di antara muka, kami menggunakan defaultkata kunci. Sebagai contoh,

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

Mengapa kaedah lalai?

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.

Walau bagaimanapun, peraturan untuk mengira luasnya berbeza untuk poligon yang berbeza. Oleh itu, getArea()disertakan tanpa pelaksanaan.

Mana-mana kelas yang menerapkan Polygon mesti menyediakan pelaksanaan getArea().

Artikel menarik...