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

在Java中,可以使用嵌套类实现类似Objective-C中协议和实现结合的效果。公共静态内部类可以与接口定义在同一源文件内,允许在不同文件中实现该接口。例如,可以创建一个公共静态接口和静态类,然后在另一个类中实现这个接口。这种结构在避免过多文件的同时提供了便利。
摘要由CSDN通过智能技术生成

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

For example:

@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

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值