1

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.

user1543871
  • 355
  • 1
  • 6
  • 16

1 Answers1

2

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 1
    Take a look at this post, also very helpful to suit your needs http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom – Kenneth Clark Apr 09 '14 at 11:02