在Java中声明类文件中的接口

Pab*_*blo 1 java

在Objective-C中,我们可以在同一个头文件中定义协议和实现.例如:

@class GamePickerViewController;

@protocol GamePickerViewControllerDelegate <NSObject>
  - (void)gamePickerViewController:
    (GamePickerViewController *)controller 
    didSelectGame:(NSString *)game;
@end

@interface GamePickerViewController : UITableViewController

@property (nonatomic, weak) id <GamePickerViewControllerDelegate> delegate;
@property (nonatomic, strong) NSString *game;

@end
Run Code Online (Sandbox Code Playgroud)

这样,如果我包含.h文件,我将可以访问文件中定义的协议.我在Java中寻找类似的结构,因为我觉得它在某些情况下很有用,我想避免创建太多的文件(接口文件+类文件).那样我可以声明:

public class MyImplementation implements AnotherClass.MyInterface{
      AnotherClass otherClass;
}
Run Code Online (Sandbox Code Playgroud)

我认为接口内的嵌套类是要走的路.我是对的?或者Java中没有类似的东西?

Jam*_*mes 12

您可以嵌套类,并使嵌套类成为公共静态,这允许它们位于相同的源文件中(尽管它很常见,将它们放在一个包中并使用单独的源文件更为正常)

例如,这是允许的

public class AnotherClass {

    public static interface MyInterface{
        // Interface code
    }

    public static class MyClass{
        //class code
    }
}
Run Code Online (Sandbox Code Playgroud)

在另一个文件中

public class MyImplementation implements AnotherClass.MyInterface{

}
Run Code Online (Sandbox Code Playgroud)

另一种选择是

public interface MyInterface{
    public static class MyClass implements MyInterface{
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用MyInterface.MyClass访问该类(java.awt.geom.Point有关此类结构的示例,请参阅参考资料)

  • 我不同意嵌套类是不寻常的.在我看来,它们并不罕见,我会说基于嵌套类的Java习语是司空见惯的.例如,Builder创建设计模式依赖于静态嵌套类,还有许多其他类.Jos Java Bloch,在Effective Java 2nd Ed中,致力于一个项目"支持静态嵌套类而不是内部类". (4认同)