Java MCQ: Which of the following statements is true about static methods in interfaces in Java 8?
Answer:
Explanation:
In Java 8, static methods in interfaces can be called without an instance of the interface. They are defined using the static
keyword and are not inherited by implementing classes. Instead, they belong to the interface itself and can be invoked using the interface name.
Here’s an example of a static method in an interface:
interface MyInterface {
static void myStaticMethod() {
System.out.println("Static method in interface");
}
}
public class Main {
public static void main(String[] args) {
MyInterface.myStaticMethod();
}
}
In this example, myStaticMethod
is a static method in MyInterface
. It is called directly on the interface using MyInterface.myStaticMethod()
, without needing an instance of MyInterface
. This behavior is similar to static methods in classes, where they are associated with the class rather than instances of the class.
Static methods in interfaces provide a way to add utility or helper methods related to the interface, without affecting the implementing classes.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html