Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Accessibility of Interface members

Tags:

java

java-8

jls

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.

like image 387
Vishrant Avatar asked Mar 20 '23 23:03

Vishrant


1 Answers

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.

like image 125
Sotirios Delimanolis Avatar answered Apr 02 '23 05:04

Sotirios Delimanolis