use*_*831 0 java polymorphism 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;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能在类Calculator中使用受保护的方法?我的回答是"protected"在同一个类和子类中很有用.我也不能认为Interface中实现的类中的方法也是继承的,就像子类一样.
您不能对在子类中重写的方法添加更多限制.同样,您不能对从接口实现的方法添加更多限制.
现在,由于接口中定义的方法是默认的 - public
(是的,您不需要显式地编写它),因此您无法使您的方法protected
实现类.
原因很简单,当你使用多态时,你可以实例化你的implementing class
并在其中存储它的引用interface type
.
ICalculator calc = new Calculator(); //valid
calc.add(1, 2); // Compiler sees ICalculator method.
Run Code Online (Sandbox Code Playgroud)
现在,当您add
使用ICalculator
引用调用方法时,编译器只能看到定义的方法ICalculator
,并相应地批准访问.但是在运行时,调用的实际方法是表单Calculator
类,现在发生了什么,如果该方法实际上是从a different package
和non-subclass
- 调用的BOOOOOM
,它在运行时崩溃了.
这就是为什么不允许这样做的原因.
添加额外内容时适用相同的概念checked exception
.编译器会再次阻止你.但是,是的,你可以添加一个额外的Unchecked Exception
,因为那些被简单地忽略了Compiler
.