December 22, 2014
Hot Topics:

Object Construction

  • July 1, 2005
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

This series, The Object-Oriented Thought Process, is intended for someone just learning an object-oriented language and wants to understand the basic concepts before jumping into the code or someone who wants to understand the infrastructure behind an OOP language they are already using. Click here to start at the beginning of the series.

In keeping with the code examples used in the previous articles, Java will be the language used to implement the concepts in code. One of the reasons that I like to use Java is that you can download the Java compiler for personal use at the Sun Microsystems Web site http://java.sun.com/. You can download the J2SE 1.4.2 SDK (software development kit) to compile and execute these applications and I will provide the code listings for all examples in this article. I have the SDK 1.4.0 loaded on my machine. I will also provide figures and the output (when appropriate) for these examples. See the previous articles in this series for detailed descriptions for compiling and running all the code examples in this series.

In the last column, I focused on what I call object responsibility. Object responsibility refers to the design concept that requires all objects to provide (or at least know how to find) any services that it may need to function properly. This concept is very important when it comes to moving objects across a network. One of these responsibilities involves the way that an object constructs itself. Proper construction puts the object in a safe-state and is efficient with computer memory. In this article, you will explore the art and science of constructing objects.

Constructing an Object

One of the more confusing aspects of moving from structured programming to object-oriented programming is the concept of constructing an object. Perhaps the reason for this is that there is really no comparable concept in structured programming. Object-oriented programming languages, at least the ones I have used, have a feature called a constructor. This is a physical piece of code (in fact, it is a special type of method) that is used to construct and initialize objects. Whereas it is true that these tasks can be accomplished in structured code in various ways (obviously, you can initialize variables in a structured program), the fact that constructors are built into the language makes constructing objects much safer—safe in the sense that the compiler and runtime environment can do a lot of the safety checks for you.

This topic of built-in functionality is a major theme throughout this series. This is because built-in functionality is a major design goal of object-oriented technologies. You saw this in the last column when the compiler was able to enforce the contract regarding the abstract methods. If you design your system properly, you can use the features of the object-oriented languages, compilers, and runtimes to assist you in building safe, reusable objects.

Constructors

Constructors are a new concept for people doing structured programming. Constructors do not normally exist in non-O-O languages such as C and Basic. Earlier, you learned about special methods that are used to construct objects. In Java and C++, as well as other O-O languages, constructors are methods that share the same name as the class and have no return type. For example, a constructor for the Cabbie class would look like this:

public class Cabbie {
   public Cabbie(){
      /* code to construct the object */
   }
}

The compiler will recognize that the method name is identical to the class name and consider the method a constructor. Note that a constructor does not have a return value. If you provide a return value, the compiler will not treat the method as a constructor—it will simply be treated as just another method.

When Is a Constructor Called?

When a new object is created, one of the first things to occur is that the constructor is called. Check out the following code:

class Test {
   public static void main(String args[]) {
      Cabbie myCabbie = new Cabbie();
   }
}

The new keyword indicates that a new instance of the Cabbie class is constructed, thus allocating the required memory. At this point, the constructor is called, passing the arguments in the parameter list (in this case there aren't any). The developer must do the appropriate initialization within the constructor—you will learn about this later.

Thus, the code new Cabbie() will instantiate a Cabbie object and call the Cabbie() method, which is the constructor.

What's Inside a Constructor?

Perhaps the most important function of a constructor is to initialize the memory allocated when the new keyword is encountered. In short, code included inside a constructor should set the newly created object to its initial, stable state.

For example, if you have a counter object with an attribute called count, you need to set count to zero in the constructor:

public class Cabbie {
   int count;
   public Cabbie(){
      count = 0;
   }
}

Initializing attributes is a common, and vital, function performed within a constructor.

The Default Constructor

If you write a class and do not include a constructor, the class will still compile and you can still use it.

public class Cabbie {
   int count;
   // no explicit constructor provided by programmer!!
   public void method01(){
      count = 0;
   }
}

If the class provides no explicit constructor, such as in C++ and Java, the compiler will provide a default constructor, which would look like this:

public class Cabbie {
   int count;
   public Cabbie(){    // this is not in the source code
                       // no code - it is really empty
   }
}

It is important to realize that this code is only inserted in the bytecodes generated by the compiler. The default constructor does not show up at all in the source code. In fact, you would need to decompile the bytecodes to see it.

After the memory is allocated, the default constructor calls the constructor of the superclass—if there is one (actually there is always a superclass—every written Java class ultimately will implicitly inherit from the Object class). You will observe this point in much more detail next month.

For example, if a constructor is not provided for the Cabbie class, the following default constructor is inserted:

public class Cabbie {
   int count;
   public Cabbie(){    // this is not in the source code
      super();         // there is an implicit call to super()
   }
}

Perhaps the default constructor may be sufficient in some cases; however, in most cases some sort of memory initialization should be performed. Regardless of the situation, it is good programming practice to always include at least one constructor in a class. In any case, if there are attributes in the class, they should be initialized in a constructor.

The rule of thumb is that you should always provide a constructor, even if you do not plan on doing anything inside it. You can provide a constructor with nothing in it and then add to it later. While there is technically nothing wrong with using the default constructor provided by the compiler, it is always nice to know exactly what your code looks like. You will explore this statement in much more detail next month.





Page 1 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel