glend
glend

Reputation: 1622

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?

Upvotes: 0

Views: 56

Answers (1)

Binkan Salaryman
Binkan Salaryman

Reputation: 3058

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):

//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:

    //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. 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:

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

    Upvotes: 1

  • Related Questions