简体   繁体   中英

since all interface method are public, does that mean all implementation of interface method must be public as well

since all interface method are public, does that mean all implementation of interface method must be public as well? I have read that subclass can only assign access level that is higher than the original method. I have tried this with some code and it does seem to be true, but I was just wondering where can I find documentation regarding to this?

You can find the official documentation of that requirement in the Java Language Specification .

Quoting from 8.4.8.3. Requirements in Overriding and Hiding :

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.

If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.

If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

As in the official Java Tutorial by Oracle:

interfaces are a kind of contract all implementing classes have to stick to

This means, the signature of a method, the return type and the access modifier are not allowed to be changed.

https://docs.oracle.com/javase/tutorial/java/IandI/index.html

Also if you try to tag an interface-method with the @Override annotation, the compiler will throw an error.

Interface s are created to be an interface for using classes that implement them.

For example we implement a Comparable interface to be trusted that the class has compareTo method which can be used by other classes.

So it's not possible and I don't see a point in doing that.

I didn't found a part of documentation which exactly refers to your question but it can be understood from this part:

If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.

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