Web Development

Java interface examples

nameerror: name nltk is not defined

Interfaces in Java

what is an interface in java? Java interface is termed as a complete abstract type used to specify the behavior of a class. Interface is just like an abstract class, the difference is that, whiles abstract class can have non-abstract methods, all methods in interface are abstract, therefore it used to achieve total abstraction. It provides full data abstraction (hiding some data and showing only relevant once to it users). Interface is also termed as any service requirement specification. Interface will give you the requirement but you have to decide what you are going to use that requirement for. Example, your father might give you money (father = interface, money = requirement) But either you will buy food, water, cloth or fish with that money, it’s up to you.

Below is the official definition from oracle:

Java interface definition by oracle

An interface has the IS-A relationship and itcontains static/final constants, abstract methods, and default or static methods. When you create an interface, the java compiler by default adds public static final to all interface variables/fields. And it adds public abstract to all abstract methods. So, when you create a variable or method in interface, the JVM will add those to it by default. Example:

java interface constants

Interface is not the same as a class and here are some important points to note.

  • You create an interface with the interface keyword, and it recommended to have separate file for every single interface.
  • Interfaces are the blueprint or skeleton of a class. They only specify the requirement for what a class can do and not how.
  • When a class implements an interface, it needs to provide implementation for all the abstract class. If note, the class needs to be declared abstract so that the chain-class that extends such class will provide implementation for all the abstract class.
  • An interface cannot contain both parameter and parameterize constructor because it can not be used to create object.

Check also, Java Vs JavaScript Programming Language (Which Is Better?)

Interface declaration synthax:

interface interfaceName{
   // declare constant fields
  // declare abstract methods
  // declare default non-abstract methods
  // declare static methods
}

Example:

public interface VehicleInterface {
  // abstract methods do not have a body
  void startVehicle(String vehicleName);
}

For an object or a class to access an interface method, the interface needs to be implemented (You could view it like inheritance but it not). Also, the class needs to provide body for all the abstract methods in the interface. (The class should be declared abstract if it does not provide body for all abstract class) example.

package myjavaapp;

// Functional-interface
// an interface with only one abstract method
public interface VehicleInterface {
    // abstract methods do not have a body
    void startVehicle(String vehicleName);

}

// A class can implements an interface with the "implements" keyword
public class Main implements  VehicleInterface  {
    // Provide body for the interface abstract method
    @Override
    public void startVehicle(String vehicleName) {

    }

  public static void main(String[] args) {
   Main main = new Main();
    main.startVehicle("bicycle");
  }
}

Note: you can not create a direct object of an interface. To do so, you need to provide full implementation for the interface methods and assign it to an object of the same type.

public class Main  {

 // create interface object and implements it single abstract method
 VehicleInterface vehicleInterfaceOne = new VehicleInterface() {
   @Override
   public void startVehicle(String vehicleName) {

   }
 };

  
 // Because it a functional-interface, you could use Lambda expression introduced in Java 8
 static VehicleInterface vehicleInterfaceTwo = vehicleName -> {
  System.out.println("print "+ vehicleName);
};


  public static void main(String[] args) {
   // call the method
   vehicleInterfaceTwo.startVehicle("bycycle");
  }

}

Check also, How to validate an email address in JavaScript

Use of interface in java

  1. Data restriction or to achieve total abstraction and security – That’s only provide the required details to a service layer and hide the important once that why interface is defined as any service requirement specification.
  2. To achieve loose coupling
  3. Multiple inheritance in java is not supported, therefore we use interface to achieve multiple inheritance. A class cannot extend multiple classes in Java but it can implement multiple interfaces and that is termed as “multiple inheritance.” To achieve multiple interface, you need to separate all the interface that the class will implements with a comma.
package myjavaapp;

public interface VehicleInterface {
    void startVehicle(String vehicleName);
}

public interface PersonInterface {
    void printFirstName(String firstName);
}


// Seperate each interface with a comma
public class Main implements  VehicleInterface, PersonInterface {
    @Override
    public void startVehicle(String vehicleName) {
        
    }

    @Override
    public void printFirstName(String firstName) {

    }

    public static void main(String[] args) {
        Main main = new Main();

    }
}

What are the types of interfaces in Java?

Currently as at JDK 9, there are 2 types of interfaces in java manly:

  • Functional interface
  • Marker interface

Functional interface in java

A functional interface it’s a type of an interface that has only one abstract method, however that interface can contain other default and static methods.  Example of such interfaces already exist in Java including:

Runnable – Only the run() method for executing thread.

ItemListener – The itemStateChanged() method is the only abstract method it contains

ActionListener – The pure actionPerformed() abstract method makes it a functional interface

Functional interface example 1:

// How to create a functional interface
interface School
{
    // it should have only single abstract method
    void printSchoolName(String txt);
}

// implements the interface
public class Main implements School
{
    @Override
    public void printSchoolName(String txt)
    {
        System.out.println(txt);
    }

    public static void main(String[] args)
    {
        Main obj = new Main();
        obj.printSchoolName("Harvard institute of science");
    }
}

Output

Harvard institute of science

Example 2:

    /*
    An Interface With A Single Abstract Method is Called Functional-Interface.
    That's when you define an interface that contains a sigle method without a body. That interface is called Functional-Interface
    */

    // Functional-Interface
    public interface VehicleInterface {
        //Single abstract method
        void startVehicle(String vehicleName);
    }


    
    //Another Functional-Interface
    public interface PersonInterface {
        //Single abstract method
        void firstName(String fName);
    
        static void sayHello(){
        System.out.println("hellow world");
        }
    }
    


    // Non-Functional-Interface
    public interface VehicleInterface {
        //first abstract method
        void startVehicle(String vehicleName);
    
        //second abstract method
        void stopVehicle(String vehicleName);
    }


    //you can use the @FunctionalInterface annotation on your interface. 
    // It will warn you if the interface is not a functional-interface 
    @FunctionalInterface
    public interface VehicleInterface {
    //Single abstract method
    void startVehicle(String vehicleName);
    
    void stopVehicle(String vehicleName);
    }
    // this throws and error because there is 2 abstract methods

Check also, How to fix property assignment expected in Typescript?

Marker interface in java

When an interface is empty, it termed as marker interface. That’s it does not contain any constant field, abstract method, default or static method.

How to implement and extend interface in java to achieve multiple inheritance

When a class implements multiple interface, its multiple inheritance.

When an interface extends multiple interface, its multiple inheritance.

java interface implement interface

Example:

interface Man1 {
    void printman1();
}

interface Man2 {
    void printman2();
}

// multiple inheritance 
class person implements Man1, Man2{

    @Override
    public void printman1() {
        System.out.println("man 1");
        
    }

    @Override
    public void printman2() {
        System.out.println("man 2");
        
    }
}

// Multiple inheritance
// the class who will implement this interface must provide implementation for all the extended interfaces
interface Girl extends Man1, Man2{

}

How To Use Java interface As a method parameter?

    // INSIDE VehicleInterface.java
    public interface VehicleInterface {
        void startVehicle(String vehicleName);
    }

    // INSIDE Main.java
    public class Main implements VehicleInterface {

        // implement overriden the interface method
        @Override
        public void startVehicle(String vehicleName) {
            System.out.println(vehicleName);
        }

        // create a method that takes in an interface parameter
        // You need to pass in an object of a class that implements <VehicleInterface>
        // to this method parameter
        void stopVehicle(VehicleInterface vehicleInterface) {
            // call startVehicle() method on the VehicleInterface object passed
            vehicleInterface.startVehicle("Stop the car");
        }

        public static void main(String[] args) {
            // create object of the class
            Main main = new Main();
            main.startVehicle("Start the car"); // RESULT: Start the car
            // FIRST. it will call main.stopVehicle()
            // SECOND. it will call main.startVehicle()
            main.stopVehicle(main); // RESULT: Stop the car

        }
    }

About Justice Ankomah

computer science certified technical instructor. Who is interested in sharing (Expert Advice Only)
View all posts by Justice Ankomah →

Leave a Reply

Your email address will not be published. Required fields are marked *