What are Static Methods on interface in Java?

In Java SE 8 and later, you can define static methods on interfaces. A static method is a method associated with the class, not the instance. This means you can call a static method without creating an instance of the class.

This feature can be particularly useful when providing utility methods that act on instances of the interface. You would normally keep these in a separate utility class, but by having these on the interface itself can lead to more readable and maintainable code.

Here is a simple example:

interface MyInterface {
    static void myStaticMethod() {
        System.out.println("Static Method on Interface");
    }
}

public class Main {
    public static void main(String[] args) {
        MyInterface.myStaticMethod(); // Call without creating instance
    }
}

In this example, myStaticMethod() is a static method defined on MyInterface. You call it using the interface name (MyInterface.myStaticMethod()), without needing to create an instance of MyInterface.

Keep in mind that static methods in interfaces are not inherited by classes that implement the interface or sub-interfaces, so you always have to use the interface name when calling them.

The Stream interface in Java has several static methods that provide useful functionality for working with sequences of elements, such as collections. Here is an example that uses the Stream.of() static method, which allows you to create a Stream from a set of objects:

import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Stream.of("Hello", "World", "Interface", "Static", "Methods")
              .map(String::toUpperCase)
              .forEach(System.out::println);
    }
}

In this example, we use Stream.of() to create a Stream from a set of String objects. We then use map() to convert each string in the stream to uppercase, and forEach() to print out each string.

Here is another example, this time using the IntStream.range() static method:

import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        IntStream.range(1, 6)
                 .forEach(System.out::println);
    }
}

In this example, IntStream.range(1, 6) creates a stream of integers from 1 (inclusive) to 6 (exclusive). The forEach() method is then used to print out each integer in the stream.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.