Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of default and static method of interface.

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

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

  1. Create an interface Feature.
  2. Define an abstract method getSQRT().
  3. Define a default method square() that actually contains a body and logic to square a number.
  4. Define a static method cube() that contains logic to cube a number.
  5. Implement the interface in a class Calc (you only need to implement getSQRT).
  6. 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 default and static methods.
  • A default method allows you to add new methods with actual bodies to interfaces without breaking all the old classes that already implement that interface.
  • A static method 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.
ADVERTISEMENT