Java 8, Interface | set 2 - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Wednesday, July 6, 2016

Java 8, Interface | set 2


We strongly recommend to refer below Set 1 before moving on to this post.

Java 8 Interface | Set 1

Static method in Java 8, Interface

Java Interface static method is similar to default method except that static method is not available to the implementing class or child interface.
Let's take an example when class implements interface
public interface Animal {
 public static String identify() {
  return "I am an animal";
 }
}
public class Test implements Animal {

 public static void main(String[] args) {
  Test obj = new Test();
  // below both lines give error
  // because static method of interface not available to implementing class
  System.out.println(obj.identify()); // compile time error
  System.out.println(Test.identify()); // compile time error
 }
}
Let's take an example when interface extends interface
public interface FireBreather extends Animal{}
public class Test {

 public static void main(String[] args) {
  // below line gives error
  // because static method of interface not available to child interface
  System.out.println(FireBreather.identify()); // compile time error
 }
}
when you add a method with the same signature in an implementing class, you’re not truly hiding the static interface method.
Static method of interface is always called with interface name followed by method name.
public class Test implements Animal {

 private static String identify() {
  return "I am in test class";
 }

 public static void main(String[] args) {
  System.out.println(Test.identify()); // print I am in test class
  System.out.println(Animal.identify());// print I am an animal
  Animal animal1;
  // This static method of interface Animal can only be accessed as
  // Animal.identify
  System.out.println(animal1.identify());// compile time error
  Animal animal = new Test();
  // This static method of interface Animal can only be accessed as
  // Animal.identify
  System.out.println(animal.identify());// compile time error
 }
}
Finally, Last example of Java 8, Interface default and static method together.
public interface Animal {
 public static String identify() {
  return "I am an animal";
 }

 public default void print() {
  System.out.println(identify());
 }
}
public class Test implements Animal {
 public static void main(String[] args) {
  Animal animal = new Test();
  animal.print(); // print I am an animal
 }
}
Note: All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.

No comments :

Post a Comment