繁体   English   中英

Java:使用接口从父类调用子类方法

[英]Java : call child class method from parent class using 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);
    }
}

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

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

它应该从 Child 类调用打印方法。

当我使用接口调用方法时

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

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

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

所以任何建议或答案都非常感谢。

通过使用:

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
}

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

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

输出是有意义的,因为您正在创建(实例化)一个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消息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM