在Java中声明类文件中的接口 [英] Declaring Interface inside class file in Java

查看:225
本文介绍了在Java中声明类文件中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  @class GamePickerViewController; 

@protocol GamePickerViewControllerDelegate< NSObject>
- (void)gamePickerViewController:
(GamePickerViewController *)控制器
didSelectGame:(NSString *)游戏;
@end

@interface GamePickerViewController:UITableViewController

@property(nonatomic,weak)id< GamePickerViewControllerDelegate>代表;
@property(非原子,强)NSString *游戏;

@end

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

  public class MyImplementation实现AnotherClass.MyInterface {
AnotherClass otherClass;
}

我认为接口内的嵌套类是可行的方法。我是对的?或者Java中没有类似的东西?

解决方案

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



例如,这是允许的

 公共类AnotherClass {

公共静态接口MyInterface {
//接口代码
}

公共静态类MyClass {
//类代码
}
}

在另一个文件中

 公共类MyImplementation实现AnotherClass.MyInterface {

}

另一种选择是

  public interface MyInterface {
公共静态类MyClass实现MyInterface {
}
}

然后访问t他使用MyInterface.MyClass上课(参见 java.awt.geom.Point 获取此类结构的示例)


in Objective-C we can define a protocol and a implementation in the same header file. For example:

@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

This way if I include the .h file I will have access to the protocol defined inside the file. I'm looking for a similar structure in Java cause I find it useful in some cases where I would like to avoid creating too many files (interface file+class file). That way I could declare:

public class MyImplementation implements AnotherClass.MyInterface{
      AnotherClass otherClass;
}

I Think nested classes inside interfaces is the way to go. I am correct? or there's nothing similar in Java?

解决方案

You can nest classes, and have the nested class be public static, this allows them to be in the same Source file (although it is unusual, it is more normal to put them together in a package and use seperate source files)

For example this is allowed

public class AnotherClass {

    public static interface MyInterface{
        // Interface code
    }

    public static class MyClass{
        //class code
    }
}

And in another file

public class MyImplementation implements AnotherClass.MyInterface{

}

Another option would be

public interface MyInterface{
    public static class MyClass implements MyInterface{
    }
}

and then access the class with MyInterface.MyClass (see java.awt.geom.Point for an example of this sort of structure)

这篇关于在Java中声明类文件中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆