简体   繁体   English

来回转换超类和子类

[英]converting superclasses and subclasses back and forth

I wish to be able to change a subclass to a superclass then, if needed, back to its subclass to get access to all the methods and fields and modify them as required. 我希望能够将子类更改为超类,然后在需要时返回其子类,以访问所有方法和字段并根据需要对其进行修改。

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

Is this possible? 这可能吗? Does the code need to be restructured? 是否需要重组代码?

In this snippet you have GenericEvent as static type (the specification of what event is required to have) and SpecificEvent as dynamic type (the actual implementation): 在此代码段中,您将GenericEvent作为静态类型(需要指定什么event的规范),并将SpecificEvent作为动态类型(实际的实现):

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

  • If you are assuming that event is a SpecificEvent , cast to the target type: 如果您假设eventSpecificEvent ,则强制转换为目标类型:

     //unsafe cast, exception is thrown if event is not a SpecificEvent SpecificEvent specEvent = (SpecificEvent) event; 

  • In most cases you are going to check for the dynamic type first: 在大多数情况下,您将首先检查动态类型:

     if(event instanceof SpecificEvent) { //safe cast SpecificEvent specEvent = (SpecificEvent) event; } 

  • The instanceof above also checks for subclasses of SpecificEvent . 上面的instanceof还会检查SpecificEvent子类。 If you like to check explicitly that event is a SpecificEvent (and not possibly a subclass of SpecificEvent !), compare the class object of the dynamic type: 如果您想显式检查event是否是SpecificEvent (而不是SpecificEvent子类 !),请比较动态类型的类对象:

     if(event.getClass() == SpecificEvent.class) { //safe cast SpecificEvent specEvent = (SpecificEvent) event; } 
  • 声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM