我希望能够将子类更改为超类,然后根据需要返回其子类以访问所有方法和字段,并根据需要对其进行修改。
public class MainClass {
public static main(String[] args) {
SpecificEvent completeEvent = new SpecificEvent();
GenericEvent event = completeEvent;
event.fire();
// without creating a new SpecificEvent how can i change str, without using the completeEvent reference, so that event.fire() has a different result?
}
}
public abstract class GenericEvent {
public abstract void fire();
}
public class SpecificEvent extends GenericEvent {
public String str = "fired";
@Override
public void fire() {
System.out.println(str);
}
}
这可能吗?代码是否需要重组?
答案 0 :(得分:1)
在此代码段中,您将GenericEvent
作为静态类型(需要event
的规范)和SpecificEvent
作为动态类型(实际实现):
//no cast needed, because SpecificEvent IS an GenericEvent
GenericEvent event = new SpecificEvent();
event
是SpecificEvent
,则转换为目标类型:
//unsafe cast, exception is thrown if event is not a SpecificEvent
SpecificEvent specEvent = (SpecificEvent) event;
if(event instanceof SpecificEvent) {
//safe cast
SpecificEvent specEvent = (SpecificEvent) event;
}
instanceof
还会检查SpecificEvent
的子类。如果您想明确检查event
是SpecificEvent
(而不是SpecificEvent
的子类),请比较动态类型的类对象:
if(event.getClass() == SpecificEvent.class) {
//safe cast
SpecificEvent specEvent = (SpecificEvent) event;
}