[英]Calling method that exists in child classes but not in parent class
public class Parent {
....
}
public class Child1 extends Parent {
....
public void foo() {
....
}
}
public class Child2 extends Parent {
....
public void foo() {
....
}
}
這里,方法foo()
僅存在於子類中,不能添加到父類中(甚至不能添加到抽象方法中)。 在這種情況下,當我想對作為Parent
類的引用的obj
調用foo()
方法時,則需要將intanceof
與多個if..else
使用,這是我想避免的。
Parent obj = ...// Object of one of the child classes
obj.foo();
編輯:我只需要使用obj
類型作為Parent
。 否則,我將無法在Parent類中存在的obj上調用方法。
我的解決方案:我正在考慮的方法是使用foo()
方法定義一個接口FooInterface
,並讓所有子類實現該接口,然后我可以將obj
類型轉換為該接口並調用foo()方法,如下所示:
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
有更好的方法嗎? 或對此有任何改善?
多態性應用於對象引用,而不是類型。 你打電話時
FooInterface obj = ...// Object of one of the child classes
obj.foo();
子類方法foo()
被調用。
除非在父類/接口本身中聲明了除非方法,否則您不能使用父對象引用來執行此操作。
您必須將其轉換為子類,因為父類/接口除了它們之間定義的協定之外,對子類沒有任何了解。
在這里, contract
意味着abstract methods
。
您可以在不需要檢查的地方嘗試這種方式。
FooInterface sc =new Child1();
sc.foo();
...
interface FooInterface{
void foo();
}
public class Parent {
}
public class Child1 extends Parent implements FooInterface{
public void foo() {
}
}
public class Child2 extends Parent implements FooInterface{
public void foo() {
}
}
我最終采用的方法是使用foo()
方法定義一個接口FooInterface
,並讓所有子類實現該接口,然后我可以將obj類型轉換為該接口,然后像這樣調用foo()
方法:
Parent obj = ...// Object of one of the child classes
.....
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
如果只想進行類型轉換,則無需添加接口。 您可以將其轉換為所需的類並調用該方法。 例
public class HelloWorld {
public static void main(String args[]) throws FileNotFoundException {
SuperClass sc =new Child1();
if(sc instanceof Child1)//Do same for Child2
((Child1)sc).foo();
}
}
class SuperClass {
}
class Child1 extends SuperClass{
public void foo(){
System.out.println("From child1");
}
}
class Child2 extends SuperClass{
public void foo(){
System.out.println("From child2");
}
}
輸出:來自child1
您可以實現從Parent
繼承的AbstractChild
,然后擴展此類而不是Parent
:
public class Parent {
....
}
public abstract class AbstractChild extends Parent{
public abstract void foo();
}
public class Child1 extends AbstractChild {
....
public void foo() {
....
}
}
public class Child2 extends AbstractChild {
....
public void foo() {
....
}
}
因此,您只需要檢查您的實例是否是instanceof AbstractChild
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.