Java - Protected Modifier with Interface

爷,独闯天下 提交于 2019-12-12 01:17:24

问题


public interface ICalculator {

    public double multi(double a, double b);

    public int add(int a, int b);


    public int sub(int a, int b);
}

public class Calculator extends ICalculator {

    protected int add(double a, double b) {
        return a+b;
    }

    public double sub(int zahl1, int zahl2 ) {
        return a*b;
    }
}

why i can't use in the class Calculator a protected method ? My answer is that "protected" is it useful in the same class and in the subclasses . Well couldn't i also think that a method in an implemented class from Interface is also inherited, like subclasses.


回答1:


You cannot add more restriction to the method you override in the sub class.In the same way, you cannot add more restriction to the method you implement from an interface.

Now, since methods defined in an interface is by default - public (Yes, you don't need to write it explicitly), so you cannot make your method protected in implementing class.

The reason is straight, when you are working with polymorphism, you can instantiate your implementing class and store its reference in the interface type.

ICalculator calc = new Calculator();  //valid

calc.add(1, 2);   // Compiler sees ICalculator method.

Now, when you invoke the add method using ICalculator reference, compiler only sees the method defined in ICalculator, and approves access accordingly. But at runtime, the actual method invoked is form Calculator class, and what happens now, if that method is actually invoked from a different package and non-subclass -- BOOOOOM, it crashes at runtime.

That is why it's not allowed.


Same concept applies when you are adding an extra checked exception. Compiler will again stop you. But yes, you can add an extra Unchecked Exceptionthough, because those are simply ignored by the Compiler.




回答2:


From the Java Language Specification, §9.4:

Every method declaration in the body of an interface is implicitly public (§6.6).

Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.

And from the JLS, §8.4.8.3:

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

Put the rules from those two sections together and the conclusion is that any method that is part of an interface implementation must be public.




回答3:


Interfaces in Java are usage-contract of a class for its clients. So all their methods are public, and you can not apply more restriction on overridden methods.



来源:https://stackoverflow.com/questions/13599276/java-protected-modifier-with-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!