Java Q & A: Default and Static Methods in Interface in Java 8

Veröffentlicht am: 16 August 2022
auf dem Kanal: Testing Tutorialspoint
16
1

default and static methods in Interfaces:

From Java 8, interfaces are enhanced to have a method with implementation. We can use default and static keyword to create interfaces with method implementation. forEach method implementation in Iterable interface.

public interface SecondInterface {

void method1(String str);

default void log(String str){
System.out.println("I1 logging::"+str);
}

static void print(String str){
System.out.println("Printing "+str);
}
}

public class VerifyInterface implements SecondInterface {

public static void main(String[] args) {
VerifyInterface obj = new VerifyInterface();
obj.method1("Hellow ");
obj.log("Class");
SecondInterface.print("interface");
}

@Override
public void method1(String str) {
System.out.println(str+"Method1");
}

}

Java 8 uses default and static methods heavily in Collection API and default methods are added so that our code remains backward compatible.

If any class in the hierarchy has a method with the same signature, then default methods become irrelevant. The Object is the base class, so if we have equals(), hashCode() default methods in the interface, it will become irrelevant. That’s why for better clarity, interfaces are not allowed to have Object default methods.


Auf dieser Seite können Sie das Online-Video Java Q & A: Default and Static Methods in Interface in Java 8 mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Testing Tutorialspoint 16 August 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 16 Mal angesehen und es wurde von 1 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!