来回转换超类和子类

converting superclasses and subclasses back and forth

我希望能够将子类更改为超类,然后在需要时返回其子类以访问所有方法和字段并根据需要修改它们。

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);
    }
}

这可能吗?代码需要重构吗?

在此代码段中,您将 GenericEvent 作为静态类型(需要 event 的规范)和 SpecificEvent 作为动态类型(实际实现):

//no cast needed, because SpecificEvent IS an GenericEvent
GenericEvent event = new SpecificEvent();

  • 如果您假设 eventSpecificEvent,则转换为目标类型:

    //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 的子 class。如果您想明确检查 eventSpecificEvent(并且不可能是 SpecificEventsubclass!),请比较class 动态类型的对象:

    if(event.getClass() == SpecificEvent.class) {
        //safe cast
        SpecificEvent specEvent = (SpecificEvent) event;
    }