考虑以下类:
class A {
void print() {
System.out.println("A");
}
}
class B extends A implements C {
}
public interface C {
void print();
}
我收到这个错误:
The inherited method A.print() cannot hide the public abstract method in C
现在,我知道 print()
必须公开才能消除编译错误,但这背后的原因是什么?
最佳答案
答案很简单,接口(interface)方法总是公开的,或者只是使用组合而不是继承。另请注意,在覆盖方法时,您无法缩小方法的访问级别。
Oracle 文档说:
The access modifier public (§6.6) pertains to every kind of interface declaration.
关于java - 为什么方法必须公开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580541/