Article

Object Oriented Concepts in Java – Part 2

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

Static Members

If you went back and examined every code example we have seen so far, there should only remain one keyword that puzzles you. Surprisingly, it appears in the very first article in this series, and at the beginning of every Java program we have written so far:

 public static void main(String[] args) {

In case you didn't spot it, the keyword in question is static. Both methods and properties can be declared static. Static members belong to the class instead of to Objects of that class. Before I explain why the main method is declared static, let's look at a simpler case.

It might be useful to know the total number of Trees that had been created in our program. To this end, we could create a static property called totalTrees in the Tree class, and modify the constructor to increase its value by one every time a Tree was created. Then, using a static method called getTotalTrees, we could check the value at any time by calling Tree.getTotalTrees().

Here's the code for the modified Tree class:

public class Tree {        
       
 private static int totalTrees = 0;          
 private int height;        
       
 public Tree() {        
   this(0);        
 }        
       
 public Tree(int height) {        
   totalTrees = totalTrees + 1;        
   if (height < 0) this.height = 0;        
   else this.height = height;        
 }        
       
 public static int getTotalTrees() {        
   return totalTrees;        
 }        
       
 ...        
}

Static members are useful in two main situations:

  • When you want to keep track of some information shared by all members of a class (as above).
  • When it doesn't make sense to have more than one instance of a property or method.

The main function is an example of the latter case. Since it doesn't make sense to have more than once instance of the main function (i.e. a program can only have one program), it is declared static.

Another example of a static member that we have seen is the out property of the System class (also known as System.out, we have used its println method on many occasions). Since there is only one system on which this program is running, it is represented by a class containing static properties (e.g. out) and methods (e.g. exit), rather than an instance of a class.

Don't worry too much if you can't quite wrap your head around the reasoning behind the use of static members in the program and the System classes. As long as you can grasp how the tree-counting example above keeps track of the total number of Tree objects created, you're in good shape.

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

Sponsored Links