【问题标题】:Java : call child class method from parent class using interfaceJava:使用接口从父类调用子类方法
【发布时间】:2020-02-06 09:48:11
【问题描述】:

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

但是下面是形成的类和接口都是。

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);
    }
}

使用接口调用方法时的预期输出

Test test = new Parent();
test.print();

它应该从 Child 类调用 print 方法。

当我使用接口调用方法时

Test test = new Parent();
test.write();

它应该从 Parent 类调用 write 方法。

所以现在它没有发生,在这两种情况下它都是从 Parent 类调用方法。

非常感谢任何建议或回答。

【问题讨论】:

  • 您能否更新您的问题以包含用于初始化test 的代码?特别是它的类型是Child 还是Parent
  • when I call method using the interface你怎么称呼它?
  • 你能编辑你的问题来展示你是如何实例化类的吗?
  • 你能加一个minimal reproducible example吗?与您如何初始化对象以及如何调用方法有关。不相关,但您写道 Parent 覆盖了 write 方法,但未在接口中声明。
  • @HassamAbdelillah 我已经编辑了我的问题以使用 Parent 类初始化测试界面。

标签: java android parent-child


【解决方案1】:

通过使用:

Test test = new Parent();
test.write();

您的test 属于Parent 类型,并且不知道Child。因此,您的输出表明 Parent 类上的两种方法都被调用。

试试:

Test test = new Child();
test.print();   // Will call Child::print()
test.write();   // Will call Parent::write()

你应该实现你想要的。

注意要使此功能起作用,您必须将write() 添加到您的Test 接口,因此:

public interface Test {
    public void print();
    public void write(); // This is required for it to be accessible via the interface
}

【讨论】:

    【解决方案2】:

    您可能需要将其转换为 Child 类。也许像这样在它之前放一张支票:

    if (test instanceof Child) {
        ((Child) test).print();
    }
    

    【讨论】:

    • 在提出任何解决方案之前知道他是如何实例化测试是合理的:)
    【解决方案3】:

    输出有意义,因为您正在创建(实例化)Parent 类型的对象。

    当然,您的 write()print() 将遵循 Parent 实现并因此显示:

    This is write method in parent class
    

    This is parent class
    

    您必须创建 Child 实例才能以与 write()print() 实现相同的方式使用:

    Test test = new Child();
    test.write();
    test.print();
    

    这段代码将显示您所期望的。由于write() 没有Child 实现,它将显示Parent 消息

    【讨论】:

    • Test test = new Child() 会更清楚。
    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 2012-02-22
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多