Components of interface in Java

Continuing from previous topic. Interface
In this post, discussion will be on the interface body.
Lets go inside interface body !!

Interface body can contain following components:

1. constants
2. abstract methods,
3. class
4. interface
From Java 8,
5. default methods, and
6. static methods.

In Java interface,

  1. All the components constant, abstract method, class, interface, default & static method will have public scope implicitly.
  2. All the components other than abstract method & default method will have static modifier implicitly.
  3. Default methods are defined with the default modifier, and static methods with the static keyword.
  4.  All constant values defined in an interface are implicitly public, static and final.
  5.  All the nested interface are implicitly public, static
  6.  All the nested class are implicitly public, static

Interface Example:

public interface Interface1 {

  int constant1 = 2; // constant
 
  void getMethod(); // abstract method

  class Class1 { // class ( static class )
 
       String getSum(int a, int b){
           int sum = a + b;
           return " inner static class call, sum:" + sum;
       }
  }
 
  interface innerInterface {
          // static interface
  }
 
  // default method
  default String defaultMethod1() {
         return " interface1. defaultMethod1 ";
  }

  // default method  
  default String defaultMethod2() {
         return " interface1. defaultMethod2 ";
  }
 
  // static method
  static String staticMethod1() {
         return " interface1. staticMethod1 ";
  }
  
  // static method
  static String staticMethod2() {
         return " interface1. staticMethod2 ";
  }
 
}

 

3 responses to “Components of interface in Java”

  1. […] data methods } Class B extends A {  // data variables  // data methods } interface InterfaceA { // Components of Interface } interface InterfaceB extends InterfaceA { // Components of Interface […]

  2. What is the use of nested interface.

    1. Thanks for commenting post.

      Interface are designed for setting standards of implementation.

      How ever if your implementation class requires nested class with defined methods, you can use it.

      Remember implemented class can have the defined inner or static interface or may not. It is not required implement necessarily.

      And also it helps when you have name resolution among your interfaces.

      Example in Java
      Map interface have static interface Entry declared.

      The entrySet( ) method declared by the Map interface returns a Set containing the map entries.
      Each of these set elements is a Map.Entry object.

Leave a comment