这是我的场景:
public interface Father{ public void sayHi(); }
public abstract class FatherImpl implements Father{
@Override
public void sayHi() { System.out.print("Hi"); } }
然后是 child
public interface Child{}
public class ChildImpl extends FatherImpl implements Child{}
测试函数是
Child c = new ChildImpl();
c.sayHi();
这会抛出编译错误。 只有当我将子界面更改为
public interface Child{} extends Father
然后程序正常运行。
谁能帮我解释一下原因。
最佳答案
Child c = new ChildImpl();
Child
接口(interface)没有 sayHi()
方法,它在 ChildImpl
中。您将 c
引用为 Child
对象,因此您无法访问该方法。
您可以将该对象引用为 ChildImpl
或添加另一个类。
ChildImpl c = new ChildImpl();
或者
public abstract class TalkingChild {
@Override
public void sayHi() {
System.out.print("Hi");
}
}
或者
public interface TalkingChild {
public void sayHi();
}
最佳解决方案完全取决于您的具体场景。
关于java - 从java中的抽象类扩展覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791478/