[英]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.