Java Program to demonstrate the use of default and static method of interface.
Objective
Write a Java program to demonstrate default and static methods introduced in Java 8 interfaces.
Algorithm / Approach
- Create an interface
Feature. - Define an abstract method
getSQRT(). - Define a
defaultmethodsquare()that actually contains a body and logic to square a number. - Define a
staticmethodcube()that contains logic to cube a number. - Implement the interface in a class
Calc(you only need to implementgetSQRT). - In main, call all three types of methods to observe how they are accessed.
Calc.java
interface Feature {
public void getSQRT();
default void square(int a) {
System.out.println("Square- "+a*a);
}
static void cube(int a) {
System.out.println("Cube - "+a*a*a);
}
}
class Calc implements Feature{
int a = 20;
public void getSQRT() {
double x = Math.sqrt(a);
System.out.println("SQRT- "+x);
}
}
class Main {
public static void main(String[] a)
{
Calc c = new Calc();
c.getSQRT();
c.square(10);
Feature.cube(10);
}
}
Expected Output
SQRT- 4.47213595499958 Square- 100 Cube - 1000
Explanation of the Program
- Prior to Java 8, interfaces could only have abstract methods. Java 8 changed everything by introducing
defaultandstaticmethods. - A
defaultmethod allows you to add new methods with actual bodies to interfaces without breaking all the old classes that already implement that interface. - A
staticmethod in an interface works just like a static method in a class. You call it directly on the interface name itself (e.g.,Feature.cube(10)) rather than on an object instance.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Trying to call a static interface method using an object reference (e.g.,
c.cube(10)). This is illegal in Java; static interface methods must be called using the Interface name.