Reputation: 2223
I want to use a Collection
whose type is known at compile time (ArrayList
). Is there any penalty going through the parent class interface?
Collection<Integer> v = new ArrayList<>();
v.add(42);
versus
ArrayList<Integer> v = new ArrayList<>();
v.add(42);
In C++, the first case would result in a virtual function call, but not the second one. Is it the same in Java?
Upvotes: 0
Views: 60
Reputation: 44308
No, there is no penalty. Your ArrayList is exactly the same object, with exactly the same type. In fact, referring to it as a Collection is a good object-oriented practice, since you are referring to the object by its contract rather than its implementation.
Upvotes: 0
Reputation: 2890
Java uses dynamic binding for all method calls, so there is no difference (they're equally bad if you will, with the caveat that JIT optimizations will probably make them equally good).
Upvotes: 1