为什么在Java中接口变量默认是静态的和最终的?
当前回答
因为:
静态:因为我们不能有接口的对象,所以我们应该避免使用对象级成员变量,而应该使用类级变量,即静态。
最后:这样变量的值就不会有歧义(Diamond问题-多重继承)。
根据文档,接口是契约而不是实现。
参考:Abhishek Jain在quora上的回答
其他回答
摘自Philip Shaw的Java接口设计常见问题解答:
接口变量是静态的,因为Java接口不能自己实例化;变量的值必须在不存在实例的静态上下文中赋值。最后一个修饰符确保分配给接口变量的值是一个真正的常量,不能被程序代码重新分配。
源
因为其他任何东西都是实现的一部分,而接口不能包含任何实现。
设想一个web应用程序,其中定义了接口并由其他类实现它。因为你不能创建一个接口的实例来访问变量,所以你需要一个静态关键字。由于它是静态的,任何值的变化都会反映到其他实现它的实例。所以为了防止这种情况,我们将其定义为最终结果。
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
在Java早期,在接口中放置常量是一种流行的技术,但现在许多人认为这是一种令人讨厌的接口使用,因为接口应该处理对象提供的服务,而不是它的数据。同样,类使用的常量通常是实现细节,但将它们放在接口中会将它们提升到类的公共API。”
我也试过要么放静电要么不放根本没有区别。代码如下:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
@Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
在Java中,接口不允许你声明任何实例变量。使用在接口中声明的变量作为实例变量将返回编译时错误。
你可以声明一个常量变量,使用不同于实例变量的静态final。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap