HJW
HJW

Reputation: 23443

Can't call concrete implementation method if instantiated through interface

List <String> list = new ArrayList<String>();
list.trimToSize();

Since trimToSize() appears only in ArrayList, and not in the List interface, is this one of the features lost if i instantiate to an interface instead of a concrete class?

Upvotes: 1

Views: 128

Answers (1)

Nick
Nick

Reputation: 25799

You can only call the methods provided by the type you're calling on. If you wanted to call the trimToSize( ) method then you'd need to first cast list to ArrayList:

( (ArrayList) list ).trimToSize( );

Upvotes: 2

Related Questions