On
completion of this section you shall understand:
We need to
take a little detour here in order to explore two features of object oriented
programming: static variables and static methods. The two features are completely different
from each other. The only thing they have in common is the keyword static which
is applied to them, but other than that, the underlying concepts and uses are
totally different. We shall treat both
separately, beginning with the variables.
When we
create a class and declare variables inside it then we assume, correctly,
that whenever we create an object of that class we that object will have its
own copies of the variables we defined. Thus
if we created two objects of the class, each object would have its own copy
of each variable. Each copy of the variable would have its own different value
and since they would reside in different objects each would be invisible to
the other – as well as being invisible to any other object.
On the
other hand if we declare a variable as being static, then, no matter how many objects of the class we create
only one copy of that variable will exist, and the same copy will be shared by
every object of the class. Although the
same variable will be visible to all objects of the class, it is still a private member of the class and will be
invisible to all code outside of the class.
In order to
examine static variables we shall
depart temporarily from our payroll example and examine instead a fairly simple
class that is shown in Listing 8.1
Listing 8.1
|
1 |
public
class |
|
2 |
{ |
|
3 |
private
static double totalSales; |
|
4 |
private
double total; |
|
5 |
private int
amountSold; |
|
6 |
public
Sale(){} |
|
7 |
public
Sale(int amtSold, double unitPrice) |
|
8 |
{ |
|
9 |
total =
amtSold * unitPrice; |
|
10 |
totalSales
+=total; |
|
11 |
} |
|
12 |
public void
showData() |
|
13 |
{ |
|
14 |
System.out.println(total +"
" + totalSales); |
|
15 |
} |
|
16 |
} |
This
extremely simple class in designed solely for demonstrating the difference
between static and regular
variables. It can be used simply to add
up the total of a number of sales. The
first variable, totalSales, is
declared as being static at line
3. The rest of the regular variables are
declared at lines 4 and 5. At line 6 we
have a blank constructor. (If we wish to have a constructor that takes
arguments then we must have another constructor that takes no arguments.)
The constructor that we shall use begins at line 7. It takes two arguments into which the unit price and the amount sold are entered. The body of the method, beginning at line 9, calculates the value of the sale by multiplying the values of the two arguments and then stores the result in the variable total. As this variable total is a regular variable each object of the class could have its own different value for this variable. At line 10 we add the value of total to the value of the variable totalSales. Since this variable is static only one copy of it will exist. This in the first object created its value will be the same as total. On the other hand if a second object is created then, once line 10 finishes execution, the the value of totalSales will be the value of total in the second object plus the value of the same variable in the first object. As more objects are created the value of totalSales will simply be the sum of the values of all of the total variables of those objects.
In order to look at how such a class as Pay could be used we look at Listing 8.2 below.
Listing 8.2
|
1 |
public class Untitled2 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
Sale s1, s2, s3, s4, s5; |
|
6 |
s1 = new Sale(10, 10); |
|
7 |
s1.showData(); |
|
8 |
s2 = new Sale(12, 8); |
|
9 |
s2.showData(); |
|
10 |
s3 = new Sale(15, 6); |
|
11 |
s3.showData(); |
|
12 |
s4 = new Sale(20, 10); |
|
13 |
s4.showData(); |
|
14 |
s5 = new Sale(8, 10); |
|
15 |
s5.showData(); |
|
16 |
} |
|
17 |
} |
Here at line 5 we create five pointers to the class
At line 8 we create a second object and pass the values 12 and 8 to its arguments. Again at line 9 of listing 8.1 the variable total will be valued to 96. At line 10, however, remember that totalSales already has a value of 100 and thus, once line 10 completes execution, totalSales will have a value of 196.
The same processing happens at the other lines where the object’s version of total will hold the value for that sale and the static variable totalSales will be incremented by that value for each object. Below is the output of Listing 8.2.
100.0 100.0
96.0 196.0
90.0 286.0
200.0 486.0
80.0 566.0
The only methods we have used so far were inside classes and we could not call any of those methods without creating an object of the class that contained it. For example if we had a class called Person which had a public method called setName we could not use
Person.setName();
Instead we had to use the following sequence:
Person p;
p = new Person;
p.setName();
On the other hand there are methods that can be useful in particular situations such as converting Fahrenheit to Celsius and vice versa. Other commonly used functions are converting and calculating dates. As methods cannot exist in isolation in Java, but must be contained inside a class then when using those commonly used methods we mentioned it would be a waste of resources to have to create an object of an entire class just to run one of its methods. Java has a way around this problem – static methods. Simply declaring a method as static, means that we can run it without having to create an object of the class that contains it.
In order to explore the static methods we shall revert to our payroll example once more and look at a version where the methods for calculating the gross, tax and nett are all static methods.
Listing 8.3
|
1 |
public class PayMethods |
|
2 |
{ |
|
3 |
public static double calculateGross(double
hours,double rate) |
|
4 |
{ |
|
5 |
return hours * rate; |
|
6 |
} |
|
7 |
public static double calculateTax(double
gross) |
|
8 |
{ |
|
9 |
if(gross<500) |
|
10 |
return gross * .25; |
|
11 |
Else |
|
12 |
return 125 + (gross - 500)* .33; |
|
13 |
} |
|
14 |
public static double calculateNett(double
gross, double tax) |
|
15 |
{ |
|
16 |
return gross - tax; |
|
17 |
} |
|
18 |
} |
In Listing 8.3 we meet our static methods in our modified payroll application. First of all notice that the methods are quite similar to the methods in the Listing 5.1 – except that our are much shorter. In Listing 8.3 there is no method main and no class level variables. The reason for this is that the class PayMethods is not to be used as a calculation unit for processing a payroll. Instead it intended as a collection of methods that might be useful to other applications and where the methods could be called independently of each other. Since the methods are declared as static it means that they can be used without having to create an object of Paymethods.
Listing 8.4 below illustrates how we might use the methods of Listing 8.3
Listing 8.4
|
1 |
public class Untitled3 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
double hours, rate, gross, tax, nett; |
|
6 |
hours = 20; |
|
7 |
rate = 20; |
|
8 |
gross = PayMethods.calculateGross(hours,
rate); |
|
9 |
tax = PayMethods.calculateTax(gross); |
|
10 |
nett = PayMethods.calculateNett(gross,
tax); |
|
11 |
System.out.println(gross); |
|
12 |
System.out.println(tax); |
|
13 |
System.out.println(nett); |
|
14 |
} |
|
15 |
} |
This listing is almost reminiscent of our first ever programming examples. The main lines to point out are lines 8 – 10. Here the three methods of the class PayMethods are called without creating an object of that class. The calling procedure is the name of the class followed by the name of the method, both being separated by a full stop.
We now are in a position to explain another keyword in the signature of our main method – the keyword static. Java objects can only be created by Java code. Before an application runs no objects can be created. But since main has to be called at the beginning of the application it must be declared as static so that it can be called from the operating system without having to create an object of the class that contains it.
A static variable is a variable that all objects of a class will have access to. One may think of it as existing outside of the objects themselves. Even though it may exist outside the objects it will still be a private variable and apart from the objects of the class, no other code can either modify or even see it.
A static method is a method that can be called without having to create an object of the class that contains it. It is used for general purpose methods that many different applications could use. Usually those methods are grouped by category into separate classes. Thus one class may hold methods that could be used for financial accounting, while another class may hold methods for statistical analysis.