我有一個物件型別的 ArrayList,我們稱它為“父級”。我需要使用僅在其子物件中可用的方法 (.method1()),即另一個名為“子物件”的物件。我 100% 確定我試圖轉換的“父”實體的每個參考也是子實體。有沒有辦法轉換參考?(Java新手)
我正在嘗試做的事情的代表:
Child Extends Parent{...}
public void randomMethod(ArrayList<Parent> a){
for(Child c: a){
c.method1() //method1 is a method of Child but not parent using attributes Parents do not have
}
}
注意:請不要告訴我更改我預先存在的代碼,我正在使用骨架代碼。
uj5u.com熱心網友回復:
這僅在List<Parent>也是List<Child>. 如果是這種情況,那么您必須將每個父實體強制轉換為子實體。
public void randomMethod(ArrayList<Parent> a){
for(Parent p: a){
((Child)p).method1() //method1 is a method of Child but not parent using attributes Parents do not have
}
}
如果 Parent 實體不superTypes屬于 Child 類,那么上面將拋出一個類轉換例外。
這是一個例子。
class Parent {
}
class Child extends Parent {
String msg;
public Child(String msg) {
this.msg = msg;
}
public String childMethod() {
return msg;
}
}
List<Parent> list =
List.of(new Child("I am the first child"),
new Child("I am the second child"));
for (Parent p : list) {
String s = ((Child) p).childMethod();
System.out.println(s);
}
印刷
I am the first child
I am the second child
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/476342.html
上一篇:將基于函式的草圖面向物件
下一篇:無法寫入json變數c#出錯
