Article

Object Oriented Concepts in Java - Part 1

Page: 1 2 3 4 5 6 7 Next

Using the Tree Class

Okay, so now you have the blueprint of a tree. Big deal, right? Where things get interesting is when you use that blueprint to create and manipulate Tree Objects in a Java program. Create a new file in your text editor called PlantTrees.java and follow along as I talk you through writing such a program.

1  /**  
2   * PlantTrees.java  
3   * A simple Java program to try out the Tree class.  
4   */  
5  
6  class PlantTrees {

Yes, that's right -- our program is itself a Java class. When you run a Java program you are actually just providing Java with the name of a class containing a special method called main that will be executed automatically to kick off your program. Later in this series we'll see some ways to take advantage of the fact that Java programs are actually classes, but for now just let this serve as a reminder of how every part of a Java program belongs to the web of classes and Objects, even the program itself.

7    public static void main(String[] args) {

This is the start of that special main method that is executed automatically to kick off your Java program. If you look closely you'll see some resemblance between this line and the declaration of the grow method in the Tree class. Both are public methods that return nothing, as evidenced by the words public and void appearing before the name of the method. As for the meaning of static and the code appearing inside the parentheses, you'll have to wait a little longer for the answers to those mysteries.

8      System.out.println("Let's plant some trees!");

The program starts by printing out a little message explaining what the program will do. This should be nothing new to you.

9      // Create a new tree  
10     Tree tree1 = new Tree();

As the comment on line 9 suggests, line 10 achieves the feat of creating a new Tree out of thin air. This is a really important line; so let me explain it in depth. The line begins by declaring the class (type) of Object to be created (in this case, Tree). We then give a name to our new Tree (in this case, tree1). This is in fact identical to declaring a new variable by specifying the type of data it will contain followed by the name of the variable (e.g. int roomTemp).

The rest of the line is where the real magic happens. The word new is a special Java keyword that triggers the instantiation of a new Object. After new comes the name of the class to be instantiated, followed by a pair of parentheses (again, in more complex cases that we shall see later, these parentheses may not be empty).
In brief, this line says, "create a new variable of type Tree called tree1, and assign it a value of a new Tree." So in fact this line isn't just creating a Tree, it's also creating a new variable to store it in. Don't worry if this distinction is a little hazy for you at this point; later examples will serve to clarify these concepts significantly.

Now that we've created a tree, let's do something with it:

11     // Print out the tree's height  
12     System.out.println("I've created a tree with a height of " +  
13                        tree1.height + " meter(s).");

Again this should not be too unfamiliar to you. This line simply prints out a line of text like any other, except that part of the line of text takes its value from the height of the tree1 variable (tree1.height). If you simply typed height instead of tree1.height, Java would think you were referring either to a variable called height declared in this method, or a property of the PlantTrees class (the program itself). Unable to find either of these, Java would print out an error message when you tried to compile the program. In order to tell Java that you are referring to the height property of the Tree in tree1, you need to tack on tree1 followed by the dot operator (.).

The dot operator may be thought of sort of like the Java way of saying "belonging to" when you read the expression backwards. Thus, tree1.height should be read as "height belonging to tree1." Since Trees are created with a height of zero, lines 12 and 13 should print out "I've created a tree with a height of 0 meter(s)."

Calling (or triggering) methods belonging to an Object is accomplished in a similar way:

14     tree1.grow();

This line calls the grow method belonging to the Tree in tree1, causing it to grow by a meter. Again, the set of parentheses indicate that it is a method we are referring to, not a property. So after this line if we print out the height of tree1 again...

15     System.out.println("After a bit of growth, it is now up to " +  
16                        tree1.height + " meter(s) tall.");

This line will print out "After a bit of growth, it is now up to 1 meter(s) tall."

To show that each Tree has its own height value that is independent of those of the other Trees, we'll polish off this example by creating a couple more Trees and having them grow by different amounts:

17     Tree tree2 = new Tree();  
18     Tree tree3 = new Tree();  
19     tree2.grow();  
20     tree3.grow();  
21     tree2.grow();  
22     tree3.grow();  
23     tree2.grow();  
24     System.out.println("Here are the final heights:");  
25     System.out.println(" tree1: " + tree1.height + "m");  
26     System.out.println(" tree2: " + tree2.height + "m");  
27     System.out.println(" tree3: " + tree3.height + "m");  
28   }  
29 }

Save and compile this program:

C:\JavaTree> javac PlantTrees.java

Make sure that PlantTrees.class is in the same directory as Tree.class, then run your PlantTrees program:

C:\JavaTree> java PlantTrees  
Let's plant some trees!  
I've created a tree with a height of 0 meter(s).  
After a bit of growth, it is now up to 1 meter(s) tall.  
Here are the final heights:  
tree1: 1m  
tree2: 3m  
tree3: 2m

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

Sponsored Links