2-8 The final and static Keywords

final Instance Variables

We covered creating constants using the final keyword in 1-3. Using the same keyword it’s possible to define a constant within an object. For example, let’s define a constant value of 1 as the default denominator value for a Fraction object:

The DEFAULT_DENOMINATOR constant is defined on line 4 using the final keyword. Any attempt to modify this constant in the code will give a Java compiler error. It’s also private such that it can only be accessed within the current Fraction object.

On lines 9 and 38 we now use this constant to set the value of the den instance variable. There are benefits to using constants like this. For one, constants enhance the readability of the code. Secondly, if we decide to change the default denominator value we only need to change it once on line 4 and it will have an effect on lines 9 and 38 automatically. All of this makes the code easier to maintain.

Static Methods

Recall that the Math class did not require us to instantiate a Math object to be able to call its methods. If you look in the Java API for the Math class you’ll see the reason for this. All of the Math class methods are declared as static.

Static methods in Java are special because they belong to the class and not an object (i.e., instance) of it. This means that to call a static method you only need to provide the class name followed by a dot (.) followed by the static method name you’d like to call. You do not need to instantiate an object of the class. From your experience using the Math class you can probably appreciate the convenience of this.

However, when defining your own static methods there are some limitations you need to be aware of. Since you don’t need to instantiate an object to call a static method it means that any instance variables or methods that would normally be associated with an object of the class are not accessible to static methods. In other words, a static method may not call a non-static method or access any instance variables defined in its class. This makes sense, because instance variables and non-static methods only exist as part of an object.

There is one type of variable that a static method can access, however. It’s called a static class variable.

Static Class Variables

Every object we instantiate from a class has the same instance variables but with unique values for each object. For example, every Fraction object has a num and den instance variable, but each Fraction object can have different num and den values.

Sometimes it can be useful if all objects of a class share a single value of an instance variable. This way if one object of the class changes the value of the instance variable, all other objects of the class access the same value. These kinds of variables are called static class variables. A common application of this is keeping track of the number of objects of a class that have been instantiated.

On line 5 we define numberOfFractions as a private static int with an initial value of 0. The static keyword indicates that all objects of this class will share the same copy of this variable in memory. Since it’s private, an accessor has been added on lines 22 to 24. In this case, I’ve chosen to make the accessor static too so that I can call this method without having to instantiate a Fraction object to do so. I can call it directly using the class name if I choose. Making the accessor static is optional, it’s just a design decision I’ve made in this case.

Here’s a test program:

# of Fractions: 0
2/3
# of Fractions: 1
1/1
# of Fractions: 2

On line 3 we call the static method getNumberOfFractions() by prefacing it with Fraction. followed by the method name. Because it is static, getNumberOfFractions() may only access static class variables. In this case it returns the value 0 because I have not created any Fraction objects yet.

On line 5 we instantiate our first Fraction object. The constructor will add 1 to the value of the static class variable numberOfFractions. On line 7 we call the getNumberOfFactions() method again, this time using the f1 object. We could have also used the class name instead, both ways work and return the value 1. On line 9 we instantiate a second Fraction object. Again, its constructor will add one to numberOfFractions such that line 11 will return a value of 2.

In summary, you can see that both Fraction objects share the same value of the numberOfFractions static class variable, and that the static method getNumberOfFractions can be called using the class name and/or an object of the class.

Why main() is Declared static

The test code above demonstrates something else that we have seen since our very first example in 1-1. The main() method itself is declared as static! We now understand enough about static methods to appreciate why this is so.

Ordinarily, to call a method you must have an object of a class instantiated. The problem is when the JVM needs to run the main() method no FractionTest object has been (or can be) created yet – so how can the JVM run main() then? By declaring main() as static, it allows the JVM to call main() without requiring a FractionTest object to be instantiated first. This may seem like an odd thing to do, but it solves a potential “chicken and egg” problem.

Because main() is static, any other methods in the same class as main() must also be declared static. If not, the main() method would not be able to call them.

We still have not talked about the String[] args part of the main() method signature, we’ll get to this in 3-2!

Static Final Class Variables

Recall that the Math class also included two constants PI and E. If you consult the Java API for the Math class you will see that these are both declared as public static final. By now you should understand what this means. The public keyword makes them accessible outside the Math class, static means they can be accessed without an object of the class, and final means that they are constants and may not be assigned a new value. You may define your own static final class variables in this way.

Revised UML Diagram

Here is a revised UML diagram reflecting the changes above:

2-8-UMLClassDiagramNotice that final instance variables names are all UPPER_CASE just as they should be in Java code. Static class variables and methods should be underlined.

You Try!

  1. Consider the following class definition and its test class. Try to predict the output of the CounterTest program, then run it in Dr. Java to see if you are correct.

  2. Draw a UML diagram for the following code:
  3. Continue improving your Rectangle class!  Add a private static variable to keep track of the number of Rectangle objects that have been instantiated.  Include an accessor method to return this value, but no mutator method so that the value cannot be manipulated by code outside the object.

    As we will see later, to draw a Rectangle in Java we require the (x, y) coordinate of the upper-left corner of the rectangle, and its width and height (in pixels).   Depending on the parameters passed to the constructor, the upper-left coordinate may not be (x1, y1), it could actually be (x2, y2).  Write public methods called getUpperLeftX() and getUpperLeftY() that compares x1 with x2, and y1 with y2 and returns the smaller of the two values.  In other words, these methods will always return the x and y coordinate of the upper-left corner of the Rectangle.

    Next, write public methods called getWidth() and getHeight() that calculate and return the absolute difference between x1 and x2, and y1 and y2, respectively.

    Next, write a public calcArea() method that reuses the getWidth() and getHeight() methods to calculate and return the area (in pixels) of the current rectangle object as a double value.
    Finally, update the UML diagram for your Rectangle class.