Reputation: 3919
Suppose I have an interface Vehicle
and implementation Car
. The class Car
has a method called getNumberCylinders()
that is not part of the Vehicle
interface. Thus in my code I need to cast a Vehicle
instance to class Car
in order to call this method.
Does such a cast incur a performance overhead, versus the alternative of including this method into the interface and calling that method directly without the cast?
Upvotes: 2
Views: 706
Reputation: 310919
Does such a cast incur a performance overhead, versus the alternative of including this method into the interface and calling that method directly without the cast?
In this case, yes, because the object mightn't be a Car, so Java has to do a runtime check, which is how ClassCastExceptions can get thrown. JVM Specification #2.6.8.
If you have to do this kind of thing you're usually doing something wrong at the design phase. I would reconsider your object model.
Upvotes: 2
Reputation: 352
If you think all vehicles should have 'number of cylinders', then it's good to add that method to the Vehicle interface. Otherwise, casting is totally fine. At runtime, casting doesn't modify your object at all. Casting has more to do with compilation check. There is no obvious report on performance overhead due to casting operation, although Java specification itself does not guarantee it will be 0 nanosecond operation. In my application, I'll worry more on the unnecessary database hits and object creation rather than just type casting.
Upvotes: 0