Do you shy away from complicated programming language techniques? Have you never quite had the time to understand the finer details of copy constructor or linked lists? You may be missing out on some powerful problem-solving mechanisms, and author Stephen Morris leads you through them.

Like this article? We recommend

Like this article? We recommend

I've often thought that mathematics is probably the worst taught of all
subjects. If a student isn't lucky enough to build a good foundation early
on, then he can look forward to a lifetime of unnecessary mathematical angst.
It's a shame because mathematics is a lot like programming—often in
both fields there is a multiplicity of solutions, which means that mathematics
and programming exhibit many similarities.

The one thing that sets mathematicians and programmers apart is the ability
to cut down on work while still getting the job done. I discuss this in detail
in
my upcoming eBook,
but it's worth mentioning that economy of effort is a highly useful skill.
The best programmers tend to rapidly get stuck into the hardest part of a given
solution; this approach helps reduce the risk of a given project. An important
tool in this ability to reduce risk is a deep understanding of the vernacular of
a programming language—this can save much effort, i.e., if you take the
time to learn the fine details, you'll reap the rewards later on.

Every programming language has its own special wrinkles, and knowledge of
these can help in rapidly solving specific problems. In this article, I'll
look at three areas of Java that often pass under the radar of programmers: copy
constructors, cloning, and linked structures. Not fully understanding these
areas of Java can result in reduced modularity and weak encapsulation—for
example, not using copy constructors can easily result in unnecessary object
instantiations. The same is true for cloning. Likewise, not using linked data
structures can make for an unnecessarily complex data model.

Once you get to grips with these three concepts, you'll be programming
in a less complex and more object-oriented spirit. So, without further ado,
let's get started.

Factories and the Recurring Need to Copy Objects

The factory concept is a widely used design pattern in Java and other object-oriented programming languages. One of the design patterns that fulfils the needs of a factory is called the abstract factory. The purpose of the factory is for creating families of related or dependent objects without specifying concrete classes. Concrete classes are used to implement the specific object requirements. However, there is a lighter requirement than a factory that often arises where you simply want to copy an object.

When you copy an object, do you want an exact copy or do you want a new individual copy? In most cases, you will want a new individual copy and an easy way to do this is to use the copy constructor. Let's start the code section with the really simple class illustrated in Listing 1.

Listing 1 A Class with a Copy Constructor

In Listing 1, I present a very simple class that models a business document. The idea here is to use this class as a kind of template for different business document types, such as invoices, receipts, statements, and so on. If you run your own business, you get used to these pesky documents! So, when you want to instantiate an invoice object, you could use code such as that illustrated in Listing 2:

Listing 2 Document Object Instantiation

In Listing 2, I create a document object instance. The document is simple: It is typed as an invoice and it has a creation date. Obviously, a real business document management system would have many more attributes, such as revision numbers, links to other documents, and so on.

So, nothing too surprising appears in Listings 1 and 2; you can now create objects of the Document class, and each such object is provided with an object reference. For example, in Listing 2 the reference is called invoice. A real-world application would typically include methods that allow operations specific to the object; for example, an invoice object would typically allow you to mark the underlying invoice as paid or unpaid. So, it's likely that you would subclass the Document class to implement the different business document classes. I haven't done any sub classing in this case, but you get the idea.

At this point, we have a bunch of instantiated Document objects as a result of running the code in Listing 3.

Listing 3 A Bunch of Objects

Let's now suppose you want to create a copy of one of the objects in Listing 3. This is similar to the case when you want to make a copy of a Word document without changing the original. In other words, you want to create an independent copy—this is a job for the copy constructor. Listing 4 illustrates the copy constructor drawn from the code in Listing 1.

Listing 5 Are the Objects Unique?

The code in Listing 5 produces the Listing 6 output on my desktop PC:

Hash codes: 4384790 9634993 1641745 11077203

Listing 6 Hash Codes Indicating Uniqueness

As you can see from Listing 6, each object has a unique hash code, which means what? Generally speaking, in as far as is reasonably practical, Java objects that are not equal have different hash codes. This is a useful property when you want to insert such objects in a hash table based data structure. Comparing hash codes in this fashion is what's called a shallow comparison. A deep comparison involves comparing data members for each object.

So much for the copy constructor. What about cloning? Suppose you don't want to implement a copy constructor but you still want to be able to copy a given object instance. Java supports a mechanism that allows this with the advantage of a somewhat lower footprint than a copy constructor. This is provided by a special purpose interface called Copyable. If you look at the first line in Listing 1, you'll see the line:

public class Document implements Copyable

This indicates that the class implements the Copyable interface with the following code in Listing 7:

public interface Copyable
{
public Object copy();
}

Listing 7 Implementation of the Copyable interface

The code in Listing 7 is very simple: It comprises a single method that returns a Java Object and that's all there is to it! So, what happens when you run the method in Listing 7? Listing 8 illustrates the code that calls the copy() method:

Listing 8 Copying a New Object Instance

It's very simple: The second line in Listing 8 invokes the copy() method. The remainder of the code just prints the hash code for the original object and the cloned object. As you can see in Listing 9, the hash codes indicate that the two objects are unique.