简体   繁体   中英

implementing static methods for interface

suppose I have an interface:

public interface abcd{
    public int a();
    public void b();
    public void c();
    public String d(String h, String j);
}  

and I implement it in some class:

public class xyzw implements abcd{

}  

but I want the method d() to be static, but I can't do this:

public class xyzw implements abcd{
    public static void c(){
       //some code
    }
}

neither can I do this:

public interface abcd{
    public int a();
    public void b();
    public static void c();
    public String d(String h, String j);
}  

I wonder if there is something or some workaround or some language construct which allows me to make a method defined by an interface a static method?

You can define a static method in interface, but only with implementation.

public interface A {
    public static void b() {
        System.out.println("Hi");
    }
}

Overriding of static methods is not allowed in Java, because you call it on Class object, not on implementation object.

If you can implement a static method in an interface, but you cannot overwrite it, remember that a static method is referenced by the class itself and not by an instance of it.

To solve your problem maybe you could define an abstract class

No, its not possible and doesn't make any sense. An interface is meant to be implemented by subclasses you can only hava a non-abstract, implemented, static method in an interface. You could not statically call your interface method with

abcd.c()

when it has no implementation. Thats why static elements can not be overridden.

It's not possible to override static methods in java.

However, in the subclass, you can declare static method with the same name and "mask it as" the original method - which is as close as you can get.

interface a {
    public static int f() {
        return 0;
    }
}
interface b extends a {
    public static int f() {
        return 1;
    }
}
System.out.println(a.f());
>> 0

System.out.println(b.f());
>> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM