Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

My question is, What does that Line mean? and What is the Difference between an Instance Variable and the Variable defined in the Interface??

like image 229
Adil Avatar asked Jun 24 '26 03:06

Adil


1 Answers

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.

like image 51
T.J. Crowder Avatar answered Jun 26 '26 08:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!