Why I can not declare the methods as static in interface? | Core Java Forum
V
Vikrant Posted on 16/07/2021

Hi,

I have created an interface and declared the methods as static so I am getting compile error at that time?

Why I can not declare the methods as static in interface?

 

Thanks,

 

Vikrant Feddewar


Y
Yogesh Chawla Replied on 16/07/2021


See static methods are those methods which are specially created to define static variables in
the project so that means if declaring static methods is allowed in interface then
variables also need to be made by default static otherwise how static method will access them.

Remember Non static method can access both static as well as non static variables but static method
is only written for defining static variable values so this goes against the Java Rules.


Now post Java 8, there is a concept of default methods

Suppose we want to provide some implementation in interface and we don’t want this implementation to be overridden in the implementing class then you can declare that method as static inside interface.

For ex:

public interface Vehicle {

    static void defaultNumberOfGears(){
        System.out.println("Six");
    }
}

Now if we declare a class

public class Car implements Vehicle {
    
    @Override
    public void defaultNumberOfGears(){
        System.out.println("Five");
    }

    public static void main(String args[]) {
        Car car = new Car();
        car.defaultNumberOfGears();

    }
}

In the above example, you will get a compilation error in the class itself because a static method cannot be overridden in the class. This code will not compile successfully unless we don't remove @Override annotation from the class definition.