Canonical classes in Java

Canonical classes in Java - picture of a canon

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() and toString() methods of the Object class.
  • It must implement the java.io.Serializable interface.
  • It should implement the java.lang.Cloneable interface and override the clone() method of Object if there is a need for deep versus shallow copies.
  • It should implement the java.lang.Comparable interface by implementing compareTo() 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”

Leave a Comment

Your email address will not be published. Required fields are marked *

Code like a Java Guru!

Thank You

We're Excited!

Thank you for completing the form. We're excited that you have chosen to contact us about training. We will process the information as soon as we can, and we will do our best to contact you within 1 working day. (Please note that our offices are closed over weekends and public holidays.)

Don't Worry

Our privacy policy ensures your data is safe: Incus Data does not sell or otherwise distribute email addresses. We will not divulge your personal information to anyone unless specifically authorised by you.

If you need any further information, please contact us on tel: (27) 12-666-2020 or email info@incusdata.com

How can we help you?

Let us contact you about your training requirements. Just fill in a few details, and we’ll get right back to you.

Your Java tip is on its way!

Check that incusdata.com is an approved sender, so that your Java tips don’t land up in the spam folder.

Our privacy policy means your data is safe. You can unsubscribe from these tips at any time.