Java Interface Complete Tutorial

  • Post author:
  • Post category:Java

Java Interface Complete Tutorial

In this section, we will learn what the interfaces are and how to use them in Java.

What is interface in Java?

In inheritance, there are times that we want to create a set of methods and want all the subclasses to override and create their own version of the body of those methods.

One way to do this is by creating abstract classes and abstract methods.

But the problem here is that a subclass can only extend to one abstract class and not multiple of them.

This is where interface can help.

An interface like a class has a name, access specifiers and body. Inside the body of an interface we can declare abstract methods and any subclass that implements the interface should override those abstract methods.

Note: abstract methods are those that their bodies are not defined. Basically, the name and parameter of the method is declared but there’s nobody.

How to declare interface in Java? (Interface syntax)

access-specifier interface InterfaceName{/*...*/}

In order to create an interface in Java, we use the keyword `interface`.

Example: declaring interface

public interface Animal {
    void sound();
}

The name of this interface is `Animal` and we used the keyword `interface` to specify that this file is an interface and not a class.

Within the body of the interface, we’ve declared one abstract method named `sound` and so any classes that implement this interface should override this method as well.

Access modifier in interfaces:

By default, abstract methods in an interface are `public`. Also, we can’t change the access specifier of abstract methods into `protected` or `private`.

How to implement interface in Java?

To implement an interface in Java, it means to use the interface on a class. This is done via the `implements` keyword as the example to show:

Example: implementing an interface in Java via implements keyword

public class Cat implements Animal {
    @Override
    public void sound() {
        System.out.println("Meow, Meow");
    }
}

`implements` keyword

When we want to implement an interface in a class, we use the keyword `implements`. This keyword comes after the name of the class and followed by that is the name of the interface that we want to implement.

Note: a class can implement multiple interfaces. So if that’s the case, simply after the keyword `implements` put the interfaces you want for the target class and separate them via comma `,`.

In the example above, the class named `Cat` used the keyword `implements` to implement the `Animal` interface and so here we need to override all the abstract methods of this interface (which in this case there’s only one method to override).

Now we can create an object from the `Cat` class and call the `sound()` method:

public class Simple {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.sound();
    }
}

Output:

Meow, Meow

Java interface notes:

  • Just like abstract classes, an interface cannot be used to create objects from. This is because they are not fully qualified. But we can create variables of type interface to store reference to objects of type classes that implemented the interface.
  • Also, an interface cannot have a constructor.

Example: interfaces in Java

Let’s refactor the example above and create a variable of type `Animal` to store the object that is created via `Cat` class:

public class Simple {
    public static void main(String[] args) {
        Animal cat = new Cat();
        cat.sound();
    }
}

Output:

Meow, Meow

Types of members that we can set in an interface in Java:

Other than abstract methods, inside an interface we can use:

In the next 4 sections, we explained each of these members in an interface.

Multiple inheritance in Java via interfaces

The beauty of interfaces is that a class can implement multiple of them! In such case each interface is separated via comma `,` when it is being implemented in a class.

Example: interfaces and multiple inheritance

The first interface:

public interface FirstInterface {

    void firstMethodOfFirstInterface();
}

The second interface:

public interface SecondInterface {
    void secondMethodOfSecondInterface();
}

The Animal interface:

public interface Animal {
    void sound();
}

Here’s the Cat class that implemented all three interfaces:

public class Cat implements Animal,FirstInterface, SecondInterface {
    @Override
    public void sound() {
        System.out.println("Meow, Meow");
    }

    @Override
    public void firstMethodOfFirstInterface() {
        System.out.println("This method belongs to the first Interface");
    }

    @Override
    public void secondMethodOfSecondInterface() {
        System.out.println("This method belongs to the second Interface");
    }
}

As you can see, we used the keyword `implements` and after that we have the interfaces each separated via comma `,`.

Let’s create an object from the `Cat` class:

public class Simple {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.sound();
        cat.firstMethodOfFirstInterface();
        cat.secondMethodOfSecondInterface();
    }
}

Output:

Meow, Meow

This method belongs to the first Interface

This method belongs to the second Interface

Using Java interfaces as data type

We mentioned that we can use an interface as the type of variables and store the reference of objects that are of type classes that implemented the interface.

But we should know that a variable of type an interface can only access those members that are declared in the interface itself!

For example, the `Animal` interface has only one method and that is `sound () `. The `Cat` class had implemented multiple interfaces, including the `Animal`. Now if we create an object from the `Cat` class and store the reference into a variable of type `Animal`, we can use the variable to only access the `sound()` method! The other interfaces’ methods are hidden and this variable cannot access them.

Example: interface as data type

public class Simple {
    public static void main(String[] args) {
        Animal animal = new Cat();
        animal.sound();
        FirstInterface firstInterface = new Cat();
        firstInterface.firstMethodOfFirstInterface();
        SecondInterface secondInterface = new Cat();
        secondInterface.secondMethodOfSecondInterface();
    }
}

Output:

Meow, Meow

This method belongs to the first Interface

This method belongs to the second Interface

In this example:

The `animal` variable can only access to the `sound()` method.

The `firstInterface` variable can only access to the `firstMethodOfFirstInterface()` method.

And the `secondInterface` variable can only access to the `secondMethodOfSecondInterface()` method.

We can also use `down casting` on interfaces as well.

Example: Java Interfaces and downcasting

public class Simple {
    public static void main(String[] args) {
        Animal animal = new Cat();
        animal.sound();
        if (animal instanceof FirstInterface){
            FirstInterface firstInterface = (FirstInterface) animal;
            firstInterface.firstMethodOfFirstInterface();
        }
       if (animal instanceof SecondInterface){
           SecondInterface secondInterface = (SecondInterface) animal;
           secondInterface.secondMethodOfSecondInterface();
       }
    }
}

If we run this example, we will get the same output.

Note: if you don’t know what down casting means, please check the down casting section.

If a class that implements an interface also wants to extend a class, we first set the extend class via the `extends` keyword and then use the `implements` to implement the target interface.

Example: public class ClassName extends BaseClassName implements InterfaceName{…}

Java Interface and inheritance (Interface extends interface)

An interface can extend to one or more other interfaces. For this to happen we use the `extends` keyword. Just like the way we used `extends` keyword in classes to extend them, the procedure is pretty much the same when it comes to interfaces.

The important note to remember is that one interface can extend to multiple other interfaces.

Example: extending interface

package com.example.demo;

public interface Animal {
}


package com.example.demo;

public interface Animal2 {
}


package com.example.demo;

public interface Human extends Animal, Animal2{
    void printName();
}

In this example, the `Human` interface extended to the Animal and Animal2 interfaces.

This means any Class that implemented the `Human` interface, will need to override any abstract methods in the `Animal` as well as `Animal2` interfaces too.

More to Read:

Java Interface Static methods.

Java Interface Default methods.

Java Interface Private methods.

Java Functional Interfaces

Leave a Reply