Recent Posts

Monday, 29 October 2018

Static methods inside interface

☀ From 1.8 version onwards in addition to default methods we can write static methods also inside interface to define utility functions.
☀ Interface static methods by-default not available to the implementation classes hence by using implementation class reference we can’t call interface static methods. We should call interface static methods by using interface name.
package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface MyInterface {
   public static int multiply(int a, int b) {
      return a * b;
   }
}

package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test implements MyInterface {
   public static void main(String[] args) {
      Test t = new Test();
      System.out.println(t.multiply(10, 20)); // C.E
      System.out.println(Test.multiply(10,20)); // C.E
      System.out.println(MyInterface.multiply(10,20));
   }
}
☀ As interface static methods by default not available to the implementation class, overriding concept is not applicable.
☀ Based on our requirement we can define exactly same method in the implementation class, it’s valid but not overriding.
E.g 1
package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface MyInterface {
   public static int multiply(int a, int b) {
      return a * b;
   }
}
package com.ashok.java8.staticmethods;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test implements MyInterface {
   public static int multiply(int a, int b) {
      return a * b;
   }
}
     It is valid but not overriding.
E.g 2
package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface MyInterface {
   public static int multiply(int a, int b) {
      return a * b;
   }
}
package com.ashok.java8.staticmethods;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test implements MyInterface {
   public int multiply(int a, int b) {
      return a * b;
   }
}
     It is valid but not overriding.
E.g 3
package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyClass {
   private int multiply(int a, int b) {
      return a * b;
   }
}
package com.ashok.java8.staticmethods;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test extends MyClass {
   public int multiply(int a, int b) {
      return a * b;
   }
}
     It is valid but not overriding.
     From 1.8 version onwards we can write main() method inside interface and hence we can run interface directly from the command prompt. 
package com.ashok.java8.staticmethods;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface MyInterface {
   public static void main(String args[]) {
      System.out.println("Hi this is ashok..!!");
   }
}

Next Tutorial : Predicate Functional Interface 

Previous Tutorial : Default Methods in Java 8 
 

No comments:

Post a Comment