简体   繁体   中英

Is down casting considered bad practice?

So, I have a set up like below where A and B are both abstract classes.

abstract class ObjectA extends ObjectB<ObjectC> {

}

public class ObjectD extends ObjectA{

    public static void main(String[] args){
        ObjectA x = new ObjectD();
        ObjectD y = (ObjectD)x; // down cast
    }

}

I'm using a library where I want to avail of the abstract methods in ObjectB and provide a default constructor for all classes - ObjectA . I'm not sure on my approach. BTW ObjectB is part of a predefine library I'm using. ObjectA is my own class providing default properties and constructor.

I'm not so sure on my approach, doesn't seem nice?

Just to add:

ObjectA requires a type that extends ObjectA.

public abstract class ObjectA<T extends ObjectA<T>> {

}

Hence, the need for what I'm doing.

Note that in some cases you might get runtime error because by the explicit cast you're telling the compiler to trust you that you're not making errors, so it'll ignore the errors and won't detect it in compilation time.

As long as you know what you're doing, that's fine. To be safe, you can always use instanceof .

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