Java : call child class method from parent class using interface

标签 java android parent-child

我不知道这个问题是否有效,或者我在定义父类结构时做错了什么。

但是以下是类和接口(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/

相关文章:

javascript - 我的 @Input() 没有在我的 Angular 2 应用程序中传递信息

java - 哈希漏洞

glass-fish 服务器的 java 8 lambda 表达式支持

android - 如何使用 MediaPlayer 知道第一个视频帧何时出现在屏幕上

android - 使用终端创建测试项目时无法在android studio中加载主项目的project.properties

php - 将元素添加到其他元素

java - 避免 BigDecimal 添加 0 java

java - 用下一个最大的元素替换每个元素(按升序排列,不替换为 -1)

android int到十六进制转换

html - 父级父级的百分比宽度