This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
My friend always says that it's a good Java practice to have Object references in Java to be of an interface type(Left hand side should always be an interface) . I do not understand why tho. Can someone please explain?
imagine you and your friend are both writing code for a project. you have a call like:
Foo myFoo = FriendsClass.Bar();
Bar is a static method that your friend is writing in his code to return some object. if Foo is a class, then your friend is locked into returning that class, forever.
however, if Foo is an interface, your friend can return ANY class that suits his needs, as long as it implements your Foo interface. It frees him up to do whatever he wants or needs, or to refactor his code a year from now to make it better, and you don't have to touch yours.
[corrected] [ May 25, 2008: Message edited by: fred rosenberger ]
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
All three examples declare the variable with an interface type - List, Map and Collection. The reason for this is, mostly, because it helps you quite a lot if you ever need to change the implementation.
For instance, all of a sudden you find that LinkedList is better for you than ArrayList. If you had declared the list type as ArrayList, you would potentially have to change many lines of code. Furthermore, you ran the risk of calling methods only available in ArrayList. The change to LinkedList will be so much easier (just one line) if you declare the reference as List. The same holds for the other two.
The general rule is, declare variables as wide as possible. List instead of ArrayList, Component instead of JComboBox, Number instead of Integer. Only when you need functionality that is specific to a more specific type you will need to use that type in the declaration. For instance if you really need a JComboBox, and not just any Component.