我只是试图理解为什么接口中定义的所有字段都隐式地是static
和final
。保持字段static
的想法对我来说很有意义,因为你不能拥有接口的对象,但是为什么它们是final
(隐式地)呢?
任何人都知道为什么Java设计人员要在接口static
和final
中创建字段
发布于 2009-10-03 14:32:23
接口旨在指定交互契约,而不是实现细节。开发人员应该能够通过查看接口来使用实现,而不必查看实现它的类内部。
接口不允许创建其实例,因为您不能指定构造函数。所以它不能有实例状态,尽管接口字段可以定义常量,这些常量是隐式静态的和最终的。
您不能在接口中指定方法体或初始值设定项块,但从Java 8开始,您可以使用bodies指定默认方法。此功能旨在允许将新方法添加到现有接口,而不必更新所有实现。但是,如果不先创建一个实现接口的实例,您仍然不能执行这样的方法。
旁白:请注意,您可以使用匿名内部类实现一个接口:
interface Foo {
String bar();
}
class FooBar {
Foo anonymous = new Foo() {
public String bar() {
return "The Laundromat Café";
};
}
您必须提供接口的完整实现,以便匿名内部类进行编译。
new Foo()
正在使用其默认构造函数初始化匿名内部类。
发布于 2009-10-03 11:36:12
字段必须是静态的,因为它们不能是抽象的(就像方法一样)。因为它们不能是抽象的,实现者将不能在逻辑上提供字段的不同实现。
字段必须是最终的,我认为,因为字段可以被许多不同的实现者访问,允许它们是可改变的可能是有问题的(因为同步)。也是为了避免它被重新实现(隐藏)。
这只是我的想法。
发布于 2014-04-04 03:13:11
我认为要求字段是final是不适当的限制,这是Java语言设计者的错误。有时,例如树处理,当您需要在实现中设置常量时,需要在接口类型的对象上执行操作。在实现类上选择代码路径是一项繁琐的工作。我使用的变通方法是定义一个接口函数,并通过返回一个文本来实现它:
public interface iMine {
String __ImplementationConstant();
...
}
public class AClass implements iMine {
public String __ImplementationConstant(){
return "AClass value for the Implementation Constant";
}
...
}
public class BClass implements iMine {
public String __ImplementationConstant(){
return "BClass value for the Implementation Constant";
}
...
}
但是,使用以下语法会更简单、更清晰,也不容易出现异常实现:
public interface iMine {
String __ImplementationConstant;
...
}
public class AClass implements iMine {
public static String __ImplementationConstant =
"AClass value for the Implementation Constant";
...
}
public class BClass implements iMine {
public static String __ImplementationConstant =
"BClass value for the Implementation Constant";
...
}
https://stackoverflow.com/questions/1513520
复制相似问题