Question

Accessibility

Java 8 Says:

All members of interfaces lacking access modifiers are implicitly public

Java 7 says:

All members of interfaces are implicitly public.

When I tried following code:

public interface Test {
    protected int i = 10;
}

And compiled, I got

Test.java:3: error: modifier protected not allowed here
        protected int i = 10;
                      ^

Java Version: Java(TM) SE Runtime Environment (build 1.8.0-b129)

But in above Interface member declaration I am not lacking access modifier then why I am getting this error.

Was it helpful?

Solution

What you're quoting is in the JLS section on Determining Accessibility with Names

All members of interfaces lacking access modifiers are implicitly public

What you really need to be looking at is the section on interface field declarations which states

ConstantDeclaration:
    {ConstantModifier} UnannType VariableDeclaratorList ;
ConstantModifier:
    Annotation public 
    static final

and

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.

So those are the modifiers you can use. The section you quoted above refers to when you don't use any access modifier, in which case it would be implicitly public.

OTHER TIPS

An interface is supposed to mean "what you can see from outside the class". It would not make sense to add non-public variable or method. Therefore, interface does not allow protected variables or methods.

The following phrases in JLS 8 sections 9.3, 9.4, and 9.5 have not changed from JLS 7:

Every field declaration in the body of an interface is implicitly public, static, and final.

Every method declaration in the body of an interface is implicitly public.

A member type declaration in an interface is implicitly public and static.

I think that covers everything, so it seems like it was unnecessary to add "lacking access modifiers" to 6.6.1, unless they wanted to make it clear that a member with a public access modifier is explicitly public rather than implicitly public. (Not that there's any significant difference that I'm aware of.)

In any event, one must be rather careful when reading language specifications. I can see how someone looking only at the change in 6.6.1 could conclude that the intent was to relax the rules. But that isn't the case. The fact is that the quoted phrases 9.3, 9.4, and 9.5 still apply, and the wording change in 6.6.1 does not supersede that. Language specifications have to be written in a formal and mathematical manner, so it's not always correct to look at one small section, or one change in one small section, and draw conclusions from it. You really have to be aware of what the entire spec says and what other sections of the spec are related to the issue, which can be difficult.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top