Java, declaring static methods in interface
本问题已经有最佳答案,请猛点这里访问。
这个主题已经有了问题和答案,没有一个有结论性的结果。如果这不可能,那么有人能确定最佳的解决方法吗?一些答案说,这是可能的Java 8,但我的IDE(Eclipse)仍然显示错误,即使它被设置为编译器符合1.8。如果有人能让它在他们的系统上工作,请告诉我,我会解决我的系统的问题。
问题:我需要用静态和非静态方法创建一个接口。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // I need to create an interface with both static and non-static methods. public interface TestInterface { // No problem int objectMethod(); // static is an illegal modifier in an interface static int classMethod(); } // TestClass is one of many classes that will implement the interface. public class TestClass implements TestInterface { // static and non-static variables are no problem private int objectVal; public static int classVal; // this method has no problem public int objectMethod() { return objectVal; } // this one has problems because it implements a method that has problems public static int classMethod() { return classVal; } } |
我需要一个类,它将使用实现接口的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // a class that will use classes that implement from the interface // what is the syntax for this? my IDE doesnt like the implements keyword public class TestGeneric <T implements TestInterface> { // stored instances of the class private T t; public void foo() { System.out.printf("t's value is: %d ", t.objectMethod()); System.out.printf("T's value is: %d ", T.classMethod()); } } |
上面代码中的唯一问题是静态方法。我能想到的唯一解决方法是不要将任何方法声明为静态方法,而是以与静态使用最相似的方式使用它们。
最接近你要求的是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public interface TestInterface { int objectMethod(); int classMethod(); // Note: not static } public class TestClass implements TestInterface { private int objectVal; public static int classVal; public int objectMethod() { return objectVal; } public int classMethod() { return classVal; } } public class TestGeneric <T extends TestInterface> { private T t; public void foo() { System.out.printf("t's value is: %d ", t.objectMethod()); System.out.printf("T's value is: %d ", t.classMethod()); } } |
这里,