[英]need help casting classes
這是我的情況(不是實際的代碼,只是粗略的概述):
class Base {
public static Image img;
}
class A extends Base {
A() {
img = "code to get certain image here";
}
}
class B extends Base {
B() {
img = "code to get certain image2 here";
}
}
我有一個Base數組,但是其中一些將是A或B。我想獲取特定於該類的img實例。 例如,如果它是A的實例,它將顯示A中定義的img。但是,我不能只使用if語句,因為我將隨着時間的推移添加許多不同的類,而且我希望獲取該圖像的代碼不必更改為包括更多的課程。
只要img
字段是靜態的,恐怕就不可能。
事實是,無論何時創建新實例(類型為A
或B
), img
字段都將被覆蓋,並且img
是靜態的。 使您的img
非靜態:
class Base {
public /*static*/ Image img;
}
一切都應該開箱即用:
Base a = new A();
Base b = new B();
a.img; // Contains the image A created
b.img; // Contains the image B created
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.