CodeGym /Java Blog /Java Interfaces /Interface in Java
Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Interface in Java

Published in the Java Interfaces group
As you know, everything in Java consists of objects, and objects have state (fields) and behavior (defined by methods). The behavior of a class is what can bind it to other classes. Behavior can have different characteristics, and sometimes it can be more convenient to move it outside the class, especially when it comes to interacting with the outside world. Just like the remote control of TV is outside of the "box" itself. The remote control is an interface for user interaction with TV functions. For example, you can imagine a class that implements an abstract airplane or helicopter. Objects of both classes such as most birds can fly, and they all do it differently. Perhaps it is worth moving this feature into a separate entity, and all potential “flyers” will be inherited from this entity? If you're already familiar with abstract classes, you can just create an abstract class Flyable and “inherit” Copter and Plane classes from it. However, what if there are several such properties? For example, airplanes and helicopters can fly, but also travel on the ground. Even if we create the Ride class, we can no longer assign Copter and Plane to it. After all, each Java class has only one parent class.Interface in Java - 1Using interfaces in Java language partially solves this problem. Interfaces in Java define some functionality that doesn’t have a specific implementation, which is then implemented by classes that use these interfaces. And one class can implement many interfaces. In fact, by implementing an interface in Java, we declare that our class can do something, we report its behavior. We already carry out the concrete implementation of the behavior in the class. So. an airplane and a helicopter take off differently: an airplane needs a runway, while a helicopter usually takes off vertically. Such details are best implemented within the class.

Interfaces in Java

To define an interface in Java language, the interface keyword is used. For example:

interface Voice {
 
    void talk();
}
The interface above is called Voice. An interface in Java may define constants and methods, which may or may not have implementations. Usually, interface methods don't have an implementation, just like in this example. Methods in interfaces without implementation are like abstract methods of abstract classes. Interface methods usually don’t have access modifiers. However access is actually public by default because the purpose of an interface is to define functionality for a class implementation. Therefore, all functionality should be open for implementation. To implement an interface, use the Implements keyword while declaring your class. Moreover, if an interface contains a method with no implementation, then that method must be implemented in the implementing class.

public class Duck implements Voice {


@Override
public void voice() {
   System.out.println("Quack");
}


    }

Interface code example

Let's take a more complete example. Every (well, almost every) animal has the ability to make sounds. Let's create a Java interface Voice for this case. It has a talk() method with no implementation.

public interface Voice {
   void talk();
}
Now all classes that support the Voice interface must have an implementation of the talk() method. Let's create two classes — Cat and Dog and indicate that they implement the Voice interface. In this case, if you don’t implement a class in it, the program won’t work. Implementing methods is very simple. When calling the talk() method of an object of the Cat class, the text equivalent of a meow will be displayed on the screen, in the case of the Dog class, a bark. We will also add getters, setters and a constructor to the classes.

public class Cat implements Voice {
   String name;
   String breed;
   int year;

   public Cat(String name, String breed, int year) {
       this.name = name;
       this.breed = breed;
       this.year = year;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getBreed() {
       return breed;
   }

   public void setBreed(String breed) {
       this.breed = breed;
   }

   public int getYear() {
       return year;
   }

   public void setYear(int year) {
       this.year = year;
   }

   @Override
   public void talk() {
       System.out.println("meow...");
   }
}
public class Dog implements Voice {
   String name;
   String color;
   int year;

   public Dog(String name, String color, int year) {
       this.name = name;
       this.color = color;
       this.year = year;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getColor() {
       return color;
   }

   public void setColor(String color) {
       this.color = color;
   }

   public int getYear() {
       return year;
   }

   public void setYear(int year) {
       this.year = year;
   }

   @Override
   public void talk() {
       System.out.println("WOF WOF");
   }
}
In fact, our classes and methods implementations are very similar. Let's create another class, Parrot, with Voice support. Only the talk() method will work differently in it: the user will enter a string into the console, and the parrot will “repeat” it using the talk() method.

import java.util.Scanner;

public class Parrot implements Voice {
   String name;
   String color;
   int year;

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getColor() {
       return color;
   }

   public void setColor(String color) {
       this.color = color;
   }

   public int getYear() {
       return year;
   }

   public void setYear(int year) {
       this.year = year;
   }

   @Override
   public void talk() {
       Scanner scanner = new Scanner(System.in);
       System.out.println("WHat should I repeat after you?...");
       String s =  scanner.nextLine();
       System.out.println(s);
   }
}
Now let's create a test class and see what result the program will produce if we call the talk() method of the objects of the Cat, Dog and Parrot classes in turn.

public class InterfaceDemo {
   public static void main(String[] args) {
       Cat cat = new Cat ("Mewie", "Siam" ,2021);
       cat.talk();
       Dog dog = new Dog("Snoopy", "White and black", 2020);
       dog.talk();
       Parrot parrot = new Parrot();
       parrot.talk();
   }
}
The output is below. Green text is the one user printed in the console.
meow... WOF WOF WHat should I repeat after you?... I am very talkative and clever bird I am very talkative and clever bird

Default Methods

Prior to the JDK 8 release when implementing an interface in Java, we had to implement all of its methods in a class. At the same time, the Java interface itself could contain only method definitions without a specific implementation. JDK 8 adds new functionality — default methods. Now Java interfaces can have not only method definitions but also default implementations. They are used if the class implements the interface but doesn't implement the method. For example, let's change the talk() method in the Voice interface to the default method. We'll also write a new Voice-enabled Duck class that doesn't have an implementation of the talk method.

public interface Voice {
   default void talk() {
       System.out.println("I can talk...");
   }
}

public class Duck implements Voice {

   public void moveForward() {
       System.out.println(" Quack, I am moving forward...");
   }

   public void TurnRight(){
       System.out.println("I am turning right...");
   }
   public void TurnLeft(){
       System.out.println("I am turning left...");

   }

   public void Stop() {
       System.out.println("Quack. I am relaxing on the surface of the water...");
   }

   public void fly(){
       System.out.println("I am flying!!!");
   }

}
Now let's change our test class a bit.

public class InterfaceDemo {
   public static void main(String[] args) {
       Cat cat = new Cat ("Mewie", "Siam" ,2021);
       cat.talk();
       Dog dog = new Dog("Snoopy", "White and black", 2020);
       dog.talk();
       Duck duck = new Duck();
       duck.talk();
   }
}
The output is here:
meow... WOF WOF I can talk...
See? In objects of the Dog and Cat classes, the overridden method talk() is called, but in an object of the Duck class, the default method from interface is called. Thus, the default method is just a method without modifiers and is marked with the default keyword. We don’t have to implement the default method in the class that implements the interface, but we can override it.

Static Methods

Since JDK 8 static methods are available in Java interfaces — they are similar to class methods:

interface Voice {
     
    void talk();
     
    static void check(){
         
        System.out.println("checked...");
    }
}
To refer to a static method of an interface, just as in the case of classes, write the name of the interface and the method:

public static void main(String[] args) {
         
    Voice.check(); 
}
Interface in Java - 2

Multiple Implementation of Interfaces

If we need to apply several interfaces in Java class, then they are all listed with a comma after the word implements:

public class Duck implements Swimmable, Flyable, Voice {

    public void moveForward() {
        System.out.println(" Quack, I am moving forward...");
    }

    public void TurnRight(){
        System.out.println("I am turning right...");
    }
    public void TurnLeft(){
        System.out.println("I am turning left...");

    }

    public void Stop() {
        System.out.println("Quack. I am relaxing on the surface of the water...");
    }

    public void fly(){
        System.out.println("I am flying!!!");
    }

}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION