3

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??

Adil
  • 817
  • 1
  • 8
  • 27
  • 1
    I think that it points to the fact that you can not have an instance of an Interface, and therefor you'll never have an instance variable in an interface. – Yassin Hajaj Dec 06 '15 at 15:36

2 Answers2

3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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;
SMA
  • 36,381
  • 8
  • 49
  • 73