问题
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
.
My question is, What does that Line
mean? and What is the Difference between an Instance Variable
and the Variable defined in the Interface
??
回答1:
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. The field staticBar
is class-wide (a static field, sometimes called a "class field").
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). So that staticBar
is roughly equivalent to the one on our Foo
class before.
回答2:
This means you cant have instance variable but a constant static final variable within an interface as per JLS. For e.g.
interface MyIface {
public static final int MY_CONSTANT = 1;
}
And access it using interface name like:
int variable = MyIface.MY_CONSTANT;
来源:https://stackoverflow.com/questions/34119176/difference-between-the-terms-instance-variable-and-variables-declared-in-inte