It's my first post, so it's easy to get used to. Even though Java 9 has been released, I think it's Java 8 now.
First, create an IF with StaticIF and Default method.
package java8.staticIfAndDefaultIf;
/**
*For testing StaticIF and default methods (studying Java8)
* @author komikcomik
*
*/
public interface StaticIF {
/**This is the default method*/
public default void helloDefault() {
System.out.println("hello Default");
}
/**It's a normal method*/
public void hello();
/**Static method*/
public static void helloStatic() {
System.out.println("hello static");
}
}
Well, it seems that static methods can be implemented in IF like this. The following is the implementation of the above Static IF interface.
package java8.staticIfAndDefaultIf;
/**
*StaticIF implementation class.
* @author komikcomik
*
*/
public class StaticIFImpl implements StaticIF{
@Override
public void hello() {
System.out.println("hello in Impl");
}
}
By the way, another one. I overridden the default method.
package java8.staticIfAndDefaultIf;
/**
*StaticIF implementation class.
*I overridden the default method.
* @author komikcomik
*
*/
public class StaticIFImplDefaultOverride implements StaticIF {
@Override
public void hello() {
System.out.println("hello in ImplDefaultOverride");
}
public void helloDefault() {
System.out.println("override default");
}
}
Finally, I created a class to call these two classes.
package java8.staticIfAndDefaultIf;
/**
*A person who calls two classes that implement StaticIF.
* @author komikcomik
*
*/
public class StaticIFCaller {
public static void main(String[] args) {
StaticIF staticIF = new StaticIFImpl();
staticIF.hello(); //It comes out that it was implemented with StaticIFImpl.
staticIF.helloDefault(); //The staticIF dafault method is displayed.
StaticIF.helloStatic(); //The static method of StaticIF appears.
StaticIF staticIF2 = new StaticIFImplDefaultOverride();
staticIF2.hello(); //It comes out that it was implemented with StaticIFImplDefaultOverride
staticIF2.helloDefault(); //The contents of StaticIF have been overridden and implemented with StaticIFImplDefaultOverride.
}
}
Below is the execution result. That's as expected.
hello in Impl
hello Default
hello static
hello in ImplDefaultOverride
override default
Isn't it possible that the default method cannot be used in the case where the same process is reluctantly written in a subclass that inherits IF? StaticIF didn't seem to be very useful.
Recommended Posts