我不知道这个问题是否有效,或者我在定义父类结构时做错了什么。
但是以下是类和接口(interface)的形成。
public interface Test {
public void print();
public void write();
}
class Parent implements Test{
@Override
public void print() {
System.out.print("This is parent class");
}
@Override
public void write() {
System.out.print("This is write method in parent class");
}
}
class Child extends Parent{
@Override
public void print(){
System.out.print("This is child class);
}
}
使用接口(interface)调用方法时的预期输出
Test test = new Parent();
test.print();
它应该从 Child 类调用 print 方法。
当我使用接口(interface)调用方法时
Test test = new Parent();
test.write();
它应该从父类调用 write 方法。
所以现在它还没有发生,在这两种情况下它都从父类调用该方法。
因此,我们非常感谢任何建议或答案。
最佳答案
通过使用:
Test test = new Parent();
test.write();
您的测试
属于Parent
类型,并且不知道Child
。因此,您的输出表明 Parent
类上的两个方法都被调用。
尝试:
Test test = new Child();
test.print(); // Will call Child::print()
test.write(); // Will call Parent::write()
你应该实现你想要的。
注意为此,您必须将 write()
添加到您的 Test
接口(interface),因此:
public interface Test {
public void print();
public void write(); // This is required for it to be accessible via the interface
}
关于Java : call child class method from parent class using interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092009/