需要帮助铸造课程

时间:2014-06-09 19:37:39

标签: java class casting

这是我的情况(不是实际的代码,只是粗略的概述):

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语句,因为我将在超时时添加许多不同的类,而且我希望获取图像的代码不需要更改为包含更多课程。

1 个答案:

答案 0 :(得分:3)

只要img字段是静态的,我担心这是不可能的。

事实是,每当您创建新实例时,img字段都会被覆盖,无论是A还是B类型,原因是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