Article

Object Oriented Concepts in Java – Part 2

Page: 1 2 3 4 5 6 7 8 9 10 Next

Constructors

A constructor is a special type of method that is invoked automatically when an object is created. Constructors allow you to specify stating values for properties, and other such initialization details.

Consider once again our Tree class; specifically, the declaration of its height property (which should now be private and accompanied by accessor methods):

 private int height = 0;

It's the "= 0" part that concerns us here. Why should all new trees be of height zero? Using a constructor, we can let users of this class specify the initial height of the tree. Here's what it looks like:

 private int height;      
     
 public Tree(int height) {      
   if (height < 0) this.height = 0;      
   else this.height = height;      
 }

At first glance, this looks just like a normal method. There are two differences, however:

  • Constructors never return a value; thus, they don't have a return type (void, int, boolean, etc.) in their declaration.
  • Constructors have the same name as the class they are used to initialize. Since we are writing the Tree class, its constructor must also be named Tree. By convention, this is the only case where a method name should be capitalized.

So dissecting this line by line, we are declaring a public constructor that takes a single parameter and assigns its value to an integer variable height. Note that this is not the object property height, as we shall see momentarily. The second line checks to see if the height variable is less than zero. If it is, we set the height property of the tree to zero (since we don't want to allow negative tree heights). If not, we assign the value of the parameter to the property.

Notice that since we have a local variable called height, we must refer to the height property of the current object as this.height. this is a special variable in Java that always refers to the object in which the current code is executing. If this confuses you, you could instead name the constructor's parameter something like newHeight. You'd then be able to refer to the Object property simply as height.

Since the Tree class now has a constructor with a parameter, you must specify a value for that parameter when creating new Trees:

Tree myTree = new Tree(10); // Initial height 10

If you liked this article, share the love:
Print-Friendly Version Suggest an Article