Difference between the terms “Instance variable” and “variables declared in Interfaces”

爷,独闯天下 提交于 2019-12-10 18:58:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!