1

在 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

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

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

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

4

6 回答 6

12

您可以嵌套类,并且嵌套类是公共静态的,这允许它们在同一个源文件中(虽然不常见,但将它们放在一个包中并使用单独的源文件更正常)

例如这是允许的

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有关此类结构的示例)

于 2012-08-07T17:32:14.333 回答
2

您可以像这样嵌套类和接口,并让它们公开!但是,您不能实现/扩展类/接口,其中扩展的类嵌套在要扩展的类中

所以这行不通:

class A extends A.B {
    public class B {

    }
}

在那里公开 B 类很好,但顶级类不能扩展内部类。

于 2012-08-07T17:26:46.763 回答
1

使用嵌套类,您可以实现类似的目标:将实现与接口一起打包,例如:

public interface MyInterface
{
    public class Implementation implements MyInterface
    {

    }
}

现在你已经有了MyInterface一个具体的实现MyInterface.Implementation

于 2012-08-07T17:24:11.480 回答
0

您可以做的是定义接口,然后将默认实现作为匿名内部类,类静态变量。

interface AProtocol {
    String foo();

    static final AProtocol DEFAULT_IMPLEMENTATION = new AProtocol(){
            @Override
            public String foo(){
                return "bar!";
            }
        };
}

你是这个意思吗?

于 2012-08-07T17:23:34.897 回答
0

Java API 经常用类来做这种事情。例如JFormattedTextFiled.AbstractFormatter。请注意,声明包含static修饰符。我不明白为什么你也不能用接口来做到这一点。

于 2012-08-07T17:29:03.600 回答
0
interface B {
   public void show();

   class b implements B {
      public void show() {
         System.out.println("hello");
      }
   }
}

class A extends B.b {
   public static void main(String ar[]) {
      B.b ob=new B.b();
      ob.show();
   }
}
于 2013-07-13T12:41:06.920 回答