[英]Java : call child class method from parent class using interface
I don't know if this question is valid or I am doing something wrong with defining the parent class structure.我不知道这个问题是否有效,或者我在定义父类结构时做错了什么。
But the following are the formation of the classes and interface are.但是下面的类和接口都是形成的。
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);
}
}
Expected output when I call method using the interface使用接口调用方法时的预期输出
Test test = new Parent();
test.print();
It should call print method from the Child class.它应该从 Child 类调用打印方法。
And when I call method using interface当我使用接口调用方法时
Test test = new Parent();
test.write();
It should call write method from the Parent class.它应该从 Parent 类调用 write 方法。
So right now it's not happening, in both the cases it's calling the method from the Parent class.所以现在它没有发生,在这两种情况下它都是从 Parent 类调用方法。
So any suggestion or answer are much appreciated.所以任何建议或答案都非常感谢。
By using:通过使用:
Test test = new Parent();
test.write();
your test
is of type Parent
and is unaware of Child
.您的
test
属于Parent
类型,并且不知道Child
。 Hence your output indicates both methods on the Parent
class are called.因此,您的输出表明
Parent
类上的两个方法都被调用。
Try:尝试:
Test test = new Child();
test.print(); // Will call Child::print()
test.write(); // Will call Parent::write()
and you should achieve what you want.你应该实现你想要的。
NB For this to work, you must add write()
to your Test
interface, thus:注意要使其工作,您必须将
write()
添加到您的Test
接口,因此:
public interface Test {
public void print();
public void write(); // This is required for it to be accessible via the interface
}
You may need to cast it to the Child
class.您可能需要将其转换为
Child
类。 Maybe put a check before it like this:也许像这样在它之前放一个支票:
if (test instanceof Child) {
((Child) test).print();
}
The output makes sense because you are creating (instanciating) an objet of type Parent
.输出是有意义的,因为您正在创建(实例化)一个
Parent
类型的对象。
Naturally, your write()
and print()
will follow the Parent
implementation and therefore display :自然地,您的
write()
和print()
将遵循Parent
实现并因此显示:
This is write method in parent class
and和
This is parent class
You have to create Child instance to use in same fashion it's write()
and print()
implementations :您必须创建 Child 实例才能以相同的方式使用它的
write()
和print()
实现:
Test test = new Child();
test.write();
test.print();
this piece of code will display what you expected.这段代码将显示您所期望的。 Since
write()
has no Child
implementation it would display the Parent
message由于
write()
没有Child
实现,它将显示Parent
消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.