Alby11
Alby11

Reputation: 645

Static method inside an Interface - Java

I'm learning Java interface and i found something weird...

Given an Interface:

public interface Worker {

    public void doWork();
    static void aTestStatic() {
        System.out.println("I can be called within the Interface!");
    }


public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    Worker.aTestStatic();
}

It actually works:

I can be called within the Interface!

Why? I thought that within Interfaces is only possible to declare methods without implemention and, not being a class, they can't be called but only implemented.

Thanks in advance.

Upvotes: 0

Views: 81

Answers (2)

Derlin
Derlin

Reputation: 9881

As this article explains,

One of the biggest design change in Java 8 is with the concept of interfaces. Prior to Java 7, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.

But note that static methods are visible to interface methods only and cannot be overriden. It is helpful in some cases, like to provide utility methods (for example, with Java 8 we could move the whole Collections.XX methods inside the collection interface).

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

This is a relatively new feature of Java 8, which lets you write static implementations in interfaces.

Prior to Java 8 programmers were forced to define a class with static methods for their interface, e.g. Collections class, which consists entirely of static methods operating on various collection interfaces.

The addition of static methods to interfaces allows programmers to keep relevant functionality together with the definition of the interface, making code easier to understand and maintain.

Upvotes: 1

Related Questions