[英]Difference between the terms “Instance variable” and “variables declared in Interfaces”
I was reading about Interfaces in a Book and I came upon this Line that confused me. 我正在阅读一本书中的界面,我遇到了困扰我的这条线。
Interfaces are syntactically similar to classes, but they lack instance variables. 接口在语法上与类相似,但它们缺少实例变量。
As far as I know about Interfaces
, we can define variables inside an Interface which are by default final
. 据我所知, Interfaces
,我们可以在接口内定义默认为final
变量。
My question is, What does that Line
mean? 我的问题是,那条Line
是什么意思? and What is the Difference between an Instance Variable
and the Variable defined in the Interface
?? Instance Variable
和Variable defined in the Interface
的Variable defined in the Interface
什么区别?
My question is, What does that Line mean? 我的问题是,那条线是什么意思?
Amongst other things, it means the book's terminology is off. 除此之外,这意味着该书的术语已经关闭。 By "instance variable," they mean "instance field." “实例变量”表示“实例字段”。
An instance field is a field that is specific to an individual instance of a class. 实例字段是特定于类的单个实例的字段。 For example: 例如:
class Foo {
// Instance field:
private int bar;
// Static field:
public static final int staticBar;
}
The field bar
is per-instance, not class-wide. 字段bar
是每个实例,而不是类范围。 The field staticBar
is class-wide (a static field, sometimes called a "class field"). 字段staticBar
是类范围的( 静态字段,有时称为“类字段”)。
Interfaces don't have instance fields. 接口没有实例字段。 They do have static fields. 他们确实有静态字段。 When you do this: 当你这样做:
interface FooInterface {
int staticBar;
}
staticBar
is automatically declared public
, static
, and final
(per JLS §9.3 ). staticBar
自动声明为public
, static
和final
(根据JLS§9.3 )。 So that staticBar
is roughly equivalent to the one on our Foo
class before. 因此staticBar
大致相当于我们之前的Foo
类。
This means you cant have instance variable but a constant static final variable within an interface as per JLS . 这意味着您不能拥有实例变量,而是根据JLS在接口中使用常量静态最终变量。 For eg 例如
interface MyIface {
public static final int MY_CONSTANT = 1;
}
And access it using interface name like: 并使用接口名称访问它,如:
int variable = MyIface.MY_CONSTANT;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.