Consider Object Usage From The Start


Introduction

It is imperative that you fully understand and take steps to ensure the proper behavior of user-defined class objects within a program. Objects are considered to be well-behaved when they behave as expected and pull no surprises.

The types of behavior I refer to deal primarily with seven usage scenarios: 1) when two objects of the same type are compared against each other for equality, 2) when an object is cloned, 3) when an object is inserted into a Hashtable collection, 4) when an object needs to provide a string representation of itself, 5) when two objects of the same type must be compared to each other to determine their natural ordering, 6) when two objects of the same type must be compared to each other to determine their total ordering, and 7) when an object is serialized.

The purpose of this chapter then is to show you how to create classes whose objects behave as expected in these seven usage scenarios. Here you will learn how to override the Object class’s toString(), hashCode(), equals(), and clone() methods along with why, and under what conditions, these methods should be overridden. I will show you how to implement the Comparable and Comparator interfaces and then show you how to use objects of these types in a collection. I will also review the need for a class to implement the Serializable interface if you intend to save objects to disk or send them over a network.

The skills you learn here will save you hours of wasted time and frustration chasing down subtle, hard to trace bugs that result from ill-behaved objects.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net