posted 18 years ago
One of the principles of good Object-oriented design is to design objects that tell the cleint only what it needs to know, and hide the implementation details as much as possible. This way, you are free to change an implementation without affecting the client.
To use your example, suppose you created a JavaBean with the following property and corresponding getter/setter:
ArrayList myList = new ArrayList();
Then your class becomes an instant hit in the developer community and thousands of users download your class and start using it. Now let's suppose you're looking at the class and decide that an ArrayList isn't really the best implementation for what you're doing and decide to change it to a LinkedList. You then publish a new version of the class and tell everyone what a great improvement it is. Everyone gets excited about the new improvements and downloads the code. What happens? All the client code they created that used your class breaks! Your status changes from hero to zero. Since you changed the implementation of that one property, the signature of the getter/setter method changes, and the old client code doesn't work any more.
Now suppose you had defined it like this:
List myList = new ArrayList();
What happens when you change the implmentation? Nothing! The client code works just the same as it always did. You remain a hero!
Here's another advantage. Suppose someone wants to extend your class, and do things a little differently. When they override your method, they are free to use any implementation of the List interface they want and are not stuck with ArrayList.
[ February 15, 2007: Message edited by: Merrill Higginson ]