简体   繁体   中英

Java Interfaces — why not have private methods?

Why are methods on interfaces always public? Why can't they be private?

Because all methods on an interface are public. That's the point in having the interface -- technically it defines a contract for your class (which may have many, overlapping, contracts/interfaces). The client of your class should hold a reference to the interface and have access only to the class' published (public) methods through the interface.

I infer that you are referring to an interface declared thusly:

public interface MyInter 
{
    public void myFunc();
}

And the resulting error if you omit the public qualifier in your implementation:

MyClass.java:3: myFunc() in MyClass cannot implement myFunc() in MyInter; attempting to assign weaker access privileges; was public
    void myFunc(){}
         ^

Say you could make myFunc private. You write the following code in a different class. This should complain about you trying to use a private function you didn't have access to:

MyClass foo = new MyClass();
foo.myFunc(); // Declared private, can't call it.

But what about this:

void doSomething(MyInter foo)
{
    foo.myFunc(); // Declared public in interface, private in implementation.
}

Can we do this? According to the interface it's a public method so we should be good to go. But it's implemented as a private method so the class expects it never to be called from the outside like this, a restriction that should be enforced by the compiler. But the compiler doesn't even need to know about MyClass for this to compile. It could not even be written yet, or in an external library that may or may not ever be integrated.

Allowing implementations creates an internal inconsistency in the rules of allowable access, and the resolution to that inconsistency is to disallow the situation altogether. Anything that can call a method in an interface must be able to call it in any implementation.

The same argument holds true for overriding subclass methods. You can't "hide" them by overriding with more restrictive qualifiers.

Why is it so?

Because the JLS says so:

In the Chapter on interface declarations, JLS 9.4 says: "Every method declaration in the body of an interface is implicitly public ."

In the Chapter on class declarations, JLS 8.4.8.3 says: "The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, ..."

Engineer Dollery's answer explains why the language is designed this way.

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