简体   繁体   中英

Why must the methods of a private inner interface be public?

I have a private inner class implementing a private inner interface. I usually omit the private modifier inside private inner classes to make the code cleaner. Unfortunately, in this situation I get "can't reduce visibility error", even though I'm not actually reducing visibility.

public class Foo {
    private interface IBar{
        void foo();
    }

    private static class Bar implements IBar{
        @Override
        public void foo() { // Must be public :(
        }
    }
}

I presume there is no way to work around this?

All methods of an interface are public and abstract . That is the rule.

Only making them public makes sense because they are to be implemented by implementing classes which may be from different packages.

and even if it is an inner interface , it still is interface So rules do not change.

All methods on an interface must be declared public . Not specifying an access modifier on the foo method causes it to be assigned package protected access by default. Since package protected is less accessible than public the code is reducing the accessibility of the foo method.

All methods of an inteface are public and abstract . If you don't define any modifier then by default it is public and abstract .

The general rule of override is you can't reduce the method visibility. In side a class if you don't define any modifier then by default it will be default and default is less visible then public. So here it must be public

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM