You may have heard of canonical classes before. But what are they actually?
No, they’ve got nothing to do with cannons – I just chose that image for fun. In computer science, the term “canonical” means conforming to well-established patterns or rules. (The word canonical is from Latin and means “according to rule” – a meaning applied to religion during the Middle Ages.)
In Java, a canonical class is simply a “well-formed” or “well-behaved” class. The canonical class form is most often used for model classes (also called domain or entity classes). These are the classes that represent persistent business data.
Rules for canonical classes
A canonical class must implement the following rules:
- It must be a JavaBean (i.e. conform to the JavaBean rules discussed last week).
- It must override the
equals()
,hashCode()
andtoString()
methods of theObject
class. - It must implement the
java.io.Serializable
interface. - It should implement the
java.lang.Cloneable
interface and override theclone()
method ofObject
if there is a need for deep versus shallow copies. - It should implement the
java.lang.Comparable
interface by implementingcompareTo()
if there is a natural sort order for the class.
Defining a finalize()
method is not part of making a canonical class. A finalizer is hardly ever needed in a class.
Is it necessary?
Is it necessary to make a model class canonical? No, but model classes are most often compared, sorted and/or added to collections.
Canonical form makes it easier to do this. It leads to consistent behaviour, especially when we add model classes to different collection types.
I’m always interested in your opinion, so please leave a comment.
1 thought on “Canonical classes in Java”
Yes this is very informative Lewis.