在Java中声明类文件中的接口
在Objective-C中,我们可以在同一个头文件中定义协议和实现。 例如:
@class GamePickerViewController; @protocol GamePickerViewControllerDelegate - (void)gamePickerViewController: (GamePickerViewController *)controller didSelectGame:(NSString *)game; @end @interface GamePickerViewController : UITableViewController @property (nonatomic, weak) id delegate; @property (nonatomic, strong) NSString *game; @end
这样,如果我包含.h文件,我将可以访问文件中定义的协议。 我正在寻找Java中的类似结构,因为我觉得它在某些情况下很有用,我想避免创建太多文件(接口文件+类文件)。 这样我可以声明:
public class MyImplementation implements AnotherClass.MyInterface{ AnotherClass otherClass; }
我认为接口内的嵌套类是要走的路。 我是对的? 或者Java中没有类似的东西?
您可以嵌套类,并使嵌套类成为公共静态,这允许它们位于相同的源文件中(尽管它很常见,将它们放在一个包中并使用单独的源文件更为正常)
例如,这是允许的
public class AnotherClass { public static interface MyInterface{ // Interface code } public static class MyClass{ //class code } }
在另一个文件中
public class MyImplementation implements AnotherClass.MyInterface{ }
另一种选择是
public interface MyInterface{ public static class MyClass implements MyInterface{ } }
然后使用MyInterface.MyClass访问该类(有关此类结构的示例,请参阅java.awt.geom.Point
)
你可以像这样嵌套类和接口,让它们公开! 但是,您无法实现/扩展类扩展嵌套在要扩展它的类中的类/接口
所以这不起作用:
class A extends AB { public class B { } }
在那里公共B级是很好的,但顶级类不能扩展内部类。
使用嵌套类可以实现类似的function:将实现与接口打包在一起,例如:
public interface MyInterface { public class Implementation implements MyInterface { } }
现在你有了MyInterface
和一个具体的实现MyInterface.Implementation
。
Java API经常使用类来做这种事情。 例如JFormattedTextFiled.AbstractFormatter 。 请注意,声明包含static
修饰符。 我不明白为什么你也不能用接口做这个。
你可以做的是定义接口,然后将默认实现作为匿名内部类,类静态变量。
interface AProtocol { String foo(); static final AProtocol DEFAULT_IMPLEMENTATION = new AProtocol(){ @Override public String foo(){ return "bar!"; } }; }
你是这个意思吗?
interface B { public void show(); class b implements B{ public void show() { System.out.println("hello"); } } } class A extends Bb { public static void main(String ar[]) { Bb ob=new Bb(); ob.show(); } }