Java - 带接口的受保护修饰符 [英] Java - Protected Modifier with Interface
问题描述
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;
}
}
为什么我不能在课程计算器中使用保护方法?
我的答案是protected在同一个类和子类中很有用。好吧,我也不能认为Interface中实现的类中的方法也是继承的,就像子类一样。
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.
推荐答案
你不能为您在子类中重写的方法添加更多限制。同样,您不能对从接口实现的方法添加更多限制。
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.
现在,由于界面中定义的方法是默认的 - public
(是的,你不需要明确地写它,所以你不能在实现类时使你的方法 protected
。
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.
现在,当你调用 add
方法时使用 ICalculator
引用,编译器只能看到 ICalculator
中定义的方法,并相应地批准访问。但是在运行时,调用的实际方法是表单 Calculator
类,如果该方法实际上是从不同的包调用
和非子类
- BOOOOOM
,它在运行时崩溃。
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 Exception
though, because those are simply ignored by the Compiler
.
这篇关于Java - 带接口的受保护修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!