7

I know that it is not recommended, but why can I declare a member variable of an interface not static?

And what is the difference between a static and a not static member of an interface? I see that if I define an interface member variable as static, I can use it in the implementing class in a not-static way:

Interface:

public interface Pinuz {
    final static int a;

    public void method1();
}

Implementing class:

public class Test implements Pinuz {
    public static void main(String[] args) {

        Test t = new Test();
        int b = t.a;
    }

    @Override
    public void method1() {
        // TODO Auto-generated method stub

    }
}

I see only a warning asking me to use the member a in a static way.

2
  • Not sure what you mean. All variables in an interface are implicitly static. Commented Jan 13, 2016 at 8:26
  • Interfaces can only have static member variables. Method signatures normally are non-static because they need to be implemented (as of Java 8 there are static default implementations but those are more of a special case). Commented Jan 13, 2016 at 8:27

3 Answers 3

11

Why can I declare a member variable of an interface not static?

It is implicitly static (and final) (which means it is static even if you omit the static keyword), as stated in the JLS:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

The reason for being final is that any implementation could change the value of member, if it's not defined as final. Then the member would be a part of the implementation, but as you know an interface is a pure abstraction.

The reason for being static is that the member belongs to the interface, and not an implementation instance.

Also, being static, you should just refer it with the class-name (otherwise you'd get a compiler warning), not through some reference, so int b = t.a; should be just written as int b = Test.a;

Sign up to request clarification or add additional context in comments.

1 Comment

Ok. I was misled by the fact that you can access static variables also using the instance, as in my post. I didn't know it was possible.
1

You cannot declare a non static variable in Java interface. Every variable in interface are implicitly public, static, and final.

Comments

1

All member variables of an interface, whether you declare them to be static or not, are static

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.