Skip to content
Advertisement

why is this still need to cast in java?

error

JavaScript

right

JavaScript

DefaultLiteProcessScope extends DefaultLiteProcessScope,but it is till need to be cast?why?

Advertisement

Answer

What you are doing here is wrong. You want to return some subtype of DefaultLiteProcessScope from the build method. However, you hard code the return type like this: new DefaultLiteProcessScope(). Now think of a slightly contrived example like this.

JavaScript

And a client code that follows.

JavaScript

Now, since you have hard-coded the return type your compiler can’t vouch for the type safety of the code. I wanted it to return the sub type, however you have hard-coded the super-type instead. So, it asks you to add an explicit cast, which is fair, isn’t it? In fact, this cast fails at runtime throwing a java.lang.ClassCastException since super type DefaultLiteProcessScope cannot be cast to the subtype SubType.

How to fix.

A much better approach would be to pass in a supplier to your build method as an argument like so.

JavaScript

Here’s the new client code.

JavaScript
Advertisement