CodeBlanks Logo Icon CodeBlanks

static methods

Learn static methods inside interfaces.

Static methods inside an interface

You can define a static method inside an interface. This method is called through the interface name; it does not belong to the implementing class. It is useful for helper methods.

Example: interface Converter { static double metersToFeet(double m) { return m * 3.28084; } }. You call this method as Converter.metersToFeet(2). It is accessed through the interface name, not through an implementing class. A static method must have a body; because code that runs is needed when called. This is a clean way to group helper functions related to an interface. It is also ideal for factory methods.

Static methods as helpers

Static methods inside an interface carry helper functions related to that interface. They belong to the interface, not the implementing class; this keeps organization clean.

Example: in the Converter interface you can define a factory method like static Converter empty(). This method is independent of implementing classes. It is called as Converter.empty(). In older versions, helper methods required separate companion classes; now static methods live inside the interface. This keeps related code in one place. The call is always made through the interface name.

Practice Add a static method to the Converter interface

Define an interface Converter. Add a static double metersToFeet(double m) method; its body returns m * 3.28084;. In main call System.out.println(Converter.metersToFeet(2));.

Starter code

Main.java
// Define the Converter interface
// Add a static metersToFeet method
// Print the method result in main

Sample solution

Main.java
interface Converter {
    static double metersToFeet(double m) {
        return m * 3.28084;
    }
}
class Main {
    public static void main(String[] args) {
        System.out.println(Converter.metersToFeet(2));
    }
}

Expected output

6.56168

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the static method call

Question
double feet = ____.metersToFeet(2);
Answer
double feet = Converter.metersToFeet(2);

Explanation: A static method is called through the interface name.

2 How is a static method inside an interface called?

  • Through an instance
  • With new
  • With super
  • Through the interface name Correct answer

Explanation: It is called through the interface name; no instance needed.

3 Match the static method concepts

Term Meaning
static Helper method keyword
Converter Call name
metersToFeet Method name
return Value return

All lessons in Intermediate