You are here
Home > java > Core Java >

Java Interface

Java InterfaceEither you are a beginner or a professional in Java programming language, you must have come across the term Java Interface. As a beginner, if not, actually you have not learnt the Java language properly. Even you may not be a good Java Programmer, if you have not learnt each aspect of a Java Interface. You are expected to know about Java Interface in a deeper way. Additionally, what are the changes introduced in newer versions of JDK, especially in JDK8. For example, the introduction of default and static methods in Java Interface.

Needless so say, the introduction of new features in Java 8 has completely changed the definition of Java Interface. Before Java 8, no method with a body was allowed at all. In contrast, Java 8 onward we are allowed to have some specific methods with body which are default & static methods. However, we have separate articles to discuss in detail about default and static methods in Java interface.

Furthermore, from the interview point of view, all the facts in this article are very important. If you search on the internet, you will find various old materials about Java interface but, you have to verify whether they also cover additional facts that have been introduced Java 8 onward or not. Hence, before appearing in any Java interview, you should revise the new changes introduced in Java Interface, otherwise you will suffer.

What is Java Interface?

Theoretically, a Java Interface is an abstract type which is used to specify the behavior of a class. Since it is an abstract type, it will only represent the behavior of a class, but not the complete implementation. Abstraction is the process of hiding certain details and showing only essential information to the user. Generally, abstraction can be achieved with either interfaces or abstract classes. That’s why we can also say that an interface is a blueprint of a class. In other words, the interface provides us a mechanism to achieve abstraction.

Programmatically, definition of Java interface depends on the JDK version in the context. In other words, what will the interface contain when we write an interface in Java programming, is the programmatic definition.

Before JDK 8:

An Interface in Java is a reference type similar to a class that can contain constants as fields/variables, abstract methods and nested types. Fields are by default public, static and final whereas methods are by default public and abstract whether we declare or not.

  • Constant Variables
  • Abstract Methods
  • Nested Types

What is Nested Type?

A nested type is a class or interface which is declared within another interface or class. Since we are talking about Java Interface, an interface declared within another interface or class is known as nested interface or member interface or inner interface. The nested interfaces are used to group related interfaces so that we can maintain them easily, write more readable code and increase encapsulation. The nested interface must be referred to by the outer interface or class. It can’t be accessed directly. We can only call the nested interface by using outer interface/class name followed by dot( . ), followed by the interface name.

Example in Collection API: Whether you noticed or not, in Collection API, Entry interface inside Map interface is nested. Hence, we access it by calling Map.Entry.

For example, below code snippet demonstrates how we can declare nested interface and how to access its methods.

Example: Another Interface defined inside an Interface

interface MyInterface{ 

   void am(); 
   
   interface MyNestedInterface{   //declaring nested interface
       void nam(); 
   } 
}

class TestNested implements MyInterface.MyNestedInterface { 

    public void nam(){
        System.out.println("Hello from Nested Interface");
    } 

    public static void main(String args[]){ 
        MyInterface.MyNestedInterface message=new TestNested(); //upcasting 
        message.nam(); 
    } 
}

Note: The nested interface will have access specifier as public by default. If we try to change access specifier of interface to anything other than public, we will get compilation error. In addition, Nested interfaces are static by default. You don’t have to mark them static explicitly.

However, members within the nested interface follow the guidelines of a normal interface.

Example: Class defined inside an Interface 

Similarly, we can define a class inside an interface. When we define a class inside the interface, the Java compiler creates a static nested class. For example, let’s see how we can define a class within the interface:

interface MyInterface{ 

   class MyClass{

   } 
}

Like nested interface, here also, the nested class will have access specifier as public by default. If we try to change access specifier of the class to anything other than public, we will get compilation error. Additionally, a class declared inside an interface can only be a static class. Whether you write the static modifier or not, placing the class inside an interface declaration makes it static by default. 

However, nested types are rarely used, but we should know about it, to have complete knowledge of Java Interface.

JDK 8 Onward:

JDK 8 onward, an Interface can contain constant variables, abstract methods, default methods, static methods, nested types. However, default and static methods will have a method body, but abstract method will not. When declaring default and static methods, it is mandatory to write keywords default and static respectively. If you don’t write these keywords, the method will be considered as the abstract method by default by the compiler. Even in this case, you will not be allowed to write method body as well.

The purpose of providing default methods is to allow the developers to add new functionalities to their interfaces if needed, without breaking their older version of code.

  • Constant Variables
  • Abstract Methods
  • Nested Types
  • Default Methods
  • Static Methods

Example: 

public interface MyJava8Interface { 

    double Pi = 3.1415926536;

    void getName(String name);

    default void print() { 
          // method body
    }

    static void print() {
         // method body
    }
}

JDK 9 Onward:

In addition to all members of Java 8 interface, Java 9 introduced private methods and private static methods in interfaces. Static methods in java 8 can not be private but from java 9 onward they can be. Hence, from Java 9 onward an interface can have the following components inside it.

  • Constant Variables
  • Abstract Methods
  • Nested Types
  • Default Methods
  • Static Methods
  • Private Methods
  • Private Static Methods

For example, below code demonstrates the new features of Interface Java 9 onward.

Example:

public interface MyJava9Interface {
    
    private void method1() { 
         // method definition 
    } 
    private static void method2() {
         // method definition 
    } 
}

Why private methods in Interfaces?

Generally, these methods are used as utility methods to define other methods inside the interface. Hence, they help in improving code-reusability. FOr example, below code demonstrates the concept:

public interface MyInterface { 
   
   default void dm() { 
      System.out.println("I am a default method");
      // calling private methods inside interface
      pm(); 
      psm(); 
   } 
   private void pm() { 
      System.out.println("I am a private method"); 
   } 
   private static void psm() {
      System.out.println("I am a private static method"); 
   } 
}

What are the key rules about private methods in Interfaces?

There are some key rules about private methods inside interfaces, which we need to understand properly. They are as follows:

1) A private method must have a body. It means they can’t be declared as abstract.

2) Private methods can be accessed within the interface only.

3) We can’t override them in implementing classes as they are private.

4) Private static method can be used inside other static and non-static interface methods.

5) Private non-static methods can’t be used inside private static methods.

6) With private methods, only static & strictfp access modifiers are allowed.

For example, below code snippet demonstrates the above points.

public interface MyTestInterface {
  
    public abstract void am();
    
    public default void dm() {
        pm();   //private method inside default method
        psm();  //private static method inside other non-static method
    }

    public static void sm() {
        psm(); //private static method inside other static method
    }

    private void pm(){
        System.out.println("private method");
    } 

    private static void psm(){
        System.out.println("private static method");
    } 
}

What are some basic common rules of Java Interface?

1) While writing an interface, we use ‘interface’ keyword rather than ‘class’.

2) An interface can’t contain a constructor, hence it can’t be used to create an object.

3) While implementing an interface, we must override all of its abstract methods.

4) We can’t use private keyword while defining an interface.

5) Variables inside Interface are constants and they are implicitly public static final. The Interface cannot have instance variables. If we declare an instance variable in an interface, it must be initialized at the time of declaration only.

6) All Interface Method can have either “abstract”, “static” or “default” modifier. In case of default and static methods, they will have a method body (Since Java 8)

7) A class implementing an interface may also be an abstract class if any one or more abstract methods remain unimplemented.

8) An interface can also be declared with empty body (i.e. without any members). For example, java.util package defines EventListener interface without a body.

9) We can declare an interface within another interface or class. Such interfaces are called nested interfaces in java. For example, below code demonstrates the concept of nested interface within a class.

class MyTestClass {
   
   public interface MyNestedInterface {    // Nested Interface
       // Body of the nested interface.
   }
}

Class A implements MyTestClass.MyNestedInterface
{
  // Body of the implementing class.
}

From the above code, it is clear that how a class can implement a nested interface.

What all modifiers are allowed in a method of Interface in Java?

private, public, abstract, default, static, strictfp.

Why do we use interface?

1) The Java Interface offers a Java Programmer to achieve abstraction. As one of the OOP’s core concepts: abstraction is highly supported through this technology. Needless to say, abstraction is a process of hiding the implementation details from the user. The user will have the information only on what the object does, but not on how it does the same. However, JDK 8 onwards, the interface doesn’t provide a complete abstraction as we can define default & static methods as well. We should consider it as an exceptional case rather than rule to avoid any confusion.

2) Since Java doesn’t support multiple inheritance, and if you want a class to achieve multiple inheritances, there is only one way: using interfaces. We can achieve multiple inheritance up to some extent using interfaces. 

3) Using Java Interface, we can achieve loose coupling. Coupling specifies the dependency of one object type on another. If two objects are completely independent of each other and the changes done in one doesn’t affect the other, then both are said to be loosely coupled.

4) Interfaces are crucial for API design because they allow you to specify which methods a class should implement.

5) Interface offers us to always have a possibility to a new implementation, which could be more robust, more reliable, more performance in the later stages of the development.

What are the rules to Implement a Java Interface?

1) ‘implements’ keyword is used by classes to implement an interface.

2) A class implementing an interface can be either a normal/concrete class or an abstract class. If one or more abstract methods from the interface are unimplemented, then implementing class will be an abstract class, otherwise it will be a normal class.

3) A class can implement multiple interfaces. Furthermore, if one or more abstract methods from any of the interfaces are unimplemented, then implementing class will be an abstract class, otherwise it will be a normal class.

4) If there are two or more same methods in two interfaces and a class implements both interfaces, then it is enough to provide the implementation of the method once.

5) A concrete class must implement all the abstract methods of the interfaces, otherwise there will be a compilation error. A concrete class is a class which has no any abstract methods.

6) A class can’t implement two interfaces that have methods with the same name, but different return type.

7) Interfaces can not extend a class or implement an Interface. An interface can extend one or more interfaces.

8) If a class extends another class and also implements an interface, then by convention, the implements clause follows the extends clause.

What are the types of Interfaces in Java?

For our easy understanding of concepts on Java Interface, we can divide it in three types based on the members they have.

1) Normal Interface
2) Marker Interface
3) Functional Interface

Normal Interface is an interface which has either one or multiple number of constants, abstract methods, default methods, static methods and nested types.

Marker Interface is an interface with no abstract method. We use it to mark some specific type so that its sub-classes can use it to execute some logic from other classes.

Additionally, Functional Interface is an interface which has only one abstract method. Further, it can have any number of static, default methods and even public methods of java.lang.Object class. In fact, we use it to define Lambda Expressions & Method References by directly providing logic to an argument of a method.

What is the difference between Java Interface and a Java Class?

Below differences are based on the current features of Java interfaces(including Java 8 & Java 9) as of now.

1) We can create an object of from a class, whereas we can’t create an object from an interface.

2) A class can extend only one class, whereas a class can implement any number of interfaces.

3) We can use private, public, protected access specifiers with the methods of a class, whereas we can use only private and public access specifiers with the methods of an interface. Remember that since Java 9, we have been allowed to declare private methods in an Interface.

4) A class can extend another class and also implement one or multiple interfaces, whereas an Interface can only extend one or more interfaces.

5) At the time of declaration, the interface variable must be initialized. Otherwise, the compiler will throw an error. It is fine with the class without initializing any variable at the time of declaration.

What is the difference between Java Interface and Abstract Class?

After the introduction of new features in Java 8 & Java 9, the number of differences between these two have increased as compared to till Java 7. We already have this question in place in our Java interview Questions & Answers article. The question is ‘What is difference between Abstract class and Interface in Java 8?‘. You can follow the link to get the detailed answer. Furthermore, here we will discuss the differences and similarities between both that raised after the introduction of Java 9.

1) Java 9 onward, both can have private methods. It was not true till Java 8.

When to use Abstract class and Interface in Java?

Abstract Class

1) If you want to share code among multiple related classes.

2) If you want to use methods with access specifier other than public and private i.e. protected. This is because methods in an interface can be public and private. Remember that, Java 9 onward, interface can have private methods also.

3) If you want to declare non-static and non-final fields/variables. This is because all variables/fields in an interface are static & final by default.

Interface

1) If you want to work with unrelated classes, interface will be the best choice.

2) If you want to take advantage of multiple inheritance, go with interface.

FAQs on Java Interface

In this section, we will list down the FAQs especially interview questions that you must know before appearing in any Java Interview.

1) What is an Interface in Java?

2) What is the purpose of an Interface in Java? Why do we need an interface in Java?

3) How many types of interfaces are there in Java? What are the three interfaces in Java?

4) Can we have an implemented method in an interface? Can we have a method body in an Interface?

5) Can we have a private members in an Interface? If yes, what is the purpose of declaring a member as private?

6) What is the purpose of declaring default & static methods in an Interface?

7) What are the new features added in Java 8 in the context of the Interface?

8) What are the new features added in Java 9 in the context of the Interface?

9) What is a Functional Interface and what is its purpose?

10) Can we define another Interface within a Java Interface?

11) Can we define an Interface within a Class?

12) Have you heard about nested types in Java? What are the nested Interfaces?

13) Can we have a private abstract method in an Interface?

14) What all access modifiers are allowed for the members of an Interface?

15) Can a class implement two interfaces that have methods with the same name, but different return type?

16) If there are two or more same methods in two interfaces and a class implements both interfaces, then how will you provide the implementation of the methods?

17) Can an Interface implement another interface? Can an Interface implement multiple Interfaces?

18) Is it mandatory to implement all abstract methods of an Interface by an implementing class?

19) Can a concrete class have abstract methods? What is a concrete class?

20) Can an implementing class further be extended by another class? If yes, in which case is it possible?

21) If a class implements an Interface and it also extends another class, then by convention which keyword will come first, implements or extends?

22) What is the difference between an Interface and an abstract class?

23) When can we use Java Interface and abstract class?

24) Can we write a constructor in an Interface?

I am sure that you can answer all the questions if you have gone through each and every point of the article. Furthermore, article and number of questions will be updated time to time when necessary.

 

 

 

 

 

 

One thought on “Java Interface

Leave a Reply


Top