简体   繁体   中英

Storing subclass object as superclass and retrieving subclass later

Lets say I have classes SubClass1 and SubClass2 that extend SuperClass. I need to store all of the objects extending SuperClass in a list (List list). Now I pass the list to a function, that can figure out which SubClass the SuperClass was previously. This function should then reconvert the SuperClass back to their respective subclasses. For example,

for (SuperClass superClass : list) {
    if (superClass.getType().equals("SubClass1")
        SubClass1 subClass = (SubClass1) superClass;
    else if (superClass.getType().equals("SubClass2")
        SubClass2 subClass = (SubClass2) superClass;
}

This example will result in a class cast exception. Is there any simple solution to get this functionality?

EDIT: As mentioned in one of the answers, this code should cause an exception. Something must be wrong with the getType() method in this example. However, the solution of using the instanceof keyword solves the issue by eliminating the need for a getType() method.

Use the instanceof operator . You could transform you code to:

for (SuperClass superClass: list) {
    if (superClass instanceof SubClass1) {
        SubClass1 subClass = (SubClass1) superClass;
    }
    else if (superClass instanceof SubClass2) {
        SubClass2 subClass = (SubClass2) superClass;
    }
    else {
        // Something strange has happened, or superClass is null
    }
}

Yes,

Instead of reaching the type from object you can just test the instance of object to some type in other word you compare the types .

if(superClass instanceof SubClass1) {

  }

In case when superClass is null , the if return false.

This example doesn't throw any exception. A quick test:

List<SuperClass> list = new ArrayList<SuperClass>();
    int count = 50;
    Random random = new Random();
    while(count-- > 0) {
        if(random.nextBoolean()) {
            list.add(new SubClass1());
        } else {
            list.add(new SubClass2());
        }
    }

    for (SuperClass superClass : list ) {
        if (superClass.getType().equals("SubClass1")){
            SubClass1 subClass = (SubClass1) superClass;
            System.out.println(subClass);
        }else if (superClass.getType().equals("SubClass2")){
            SubClass2 subClass = (SubClass2) superClass;
            System.out.println(subClass);
        }
    }

If you have class cast exception, most likely getType() implementation of one of the classes returns wrong value, that's why you have class cast exception.Or one of your subclasses doesn't extend SuperClass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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