Rajinder Menu

Static methods in an Interface



Interface tutorial Series:




Similarly as default methods an interface can have static methods. Static methods can also have their bodies defined in the interface. For example

interface OurInterface {

  public void method1(); //abstract method

  //static method
  static void method2() {
    System.out.println("This is static method");
  }
}

Static methods are called within the implementing class using the interface name instead of object name as:

public class OurClass implements OurInterface{

  //Implementing an abstract method1()
  public void method1(){
    System.out.println("This is method1()");
  }

  public static void main(String s[]) {
    OurClass ourObject=new OurClass();
         ourObject.method1();
    OurInterface.method2(); //calling static method using interface      //name instead of object name
  }
}

In above code method2() is a static method. Its body is defined in the interface itself and gets inherited in the implementing class OurClass. So we need not to provide its body in OurClass. Static method method2() is called in OurClass using interface name instead of the object of OurClass i.e. ourObject.

This is also the difference between default methods and static methods in an interface that default methods can be called using implementing class object but static method can be called using only interface name instead of object name.


Static methods and Overriding

Now suppose there is a static method present in an interface and the implementing class also provides the body of that static method in its definition. For example

interface OurInterface {

  void method1();

  static void method2() {
    System.out.println("This is static method");
  }
}

public class OurFirstClass implements OurInterface{

  //Implementing an abstract method1()
  public void method1(){
    System.out.println("OurFirstClass :This is method1()");
  }

  //defining static method again in implementing class
  void method2() {
    System.out.println("Overriding static method2()");
  }

  public static void main(String s[]) {
    OurClass ourObject=new OurClass();
         ourObject.method1();
    ourInterface.method2(); //will call the static method present        //in interface.
    ourObject.method2(); //will call overrided method present in        //OurFirstClass.
  }
}

Output:

OurFirstClass :This is method1()
This is static method
Overriding static method2()

Here in this case we will say that OurFirstClass has overrided the static method2() present in interface.

I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment