CSCE155 and CSCE155H
FAQs and Interesting Questions
Q6. When is it better to use a static data member?
A6. A static data member is a class data
member. It means that if you change the
value of the data member in one instance, then the change is felt or reflected
in all instances of the same class. It
is better to use a static data member when each instance of the same class has
an opportunity to handle a change to that data member that will cause all other
instances of the same class to follow suit.
For example, suppose you have a class called MineSweeper and
you have created 4 instances/objects of this MineSweeper class. In the MineSweeper class, there is a boolean
data member called mineDetected. Now, suppose you have the following:
MineSweeper robot1 = new
MineSweeper(area1);
MineSweeper robot2 = new
MineSweeper(area2);
MineSweeper robot3 = new
MineSweeper(area3);
MineSweeper robot4 = new
MineSweeper(area4);
The
argument passed into the constructor means the area that the MineSweeper object will cover.
Now,
suppose that as soon as one robot finds a mine, all robots terminate their
sweep.
In this
case, declaring the boolean
data member mineDetected static is appropriate!
Why? As soon as one robot detects
a mine, it sets the boolean
data member to true. And then all robots
will notice the change in the boolean
value and call off their sweeps.
Q7. When is it better to use a static method?
A7. You declare a method static only if you
want it to be used by client programs without having to create the object
first. Essentially, you are creating a
global method when you declare a method static.
For example, suppose you have the following code:
class Pen {
private String
color;
private double
cost;
public void computeQuality(String color) {
if (color ==
“red”)
System.out.println(“Quality is low.”);
else
System.out.println(“Quality is high.”);
}
}
To use the
method computeQuality(),
you will need to do this in your client program:
Pen
myPen = new
Pen();
myPen.computeQuality(“blue”);
That is,
you will have to create the Pen object first before you can
access its method!
However, if
you declare the computeQuality()
method static, then it essentially becomes a global variable. Then it is okay to do this:
Pen.computeQuality(“blue”);
Pay very
close attention to the difference here.
When the method is static, we do NOT have to create an object to use the
method. But to use it, we do have to use
the class name to designate it.
When it is
better to use static methods? It is
better to declare a method static if you want the method to be used freely by
other client programs. When is that? It is when the method that you implement is
generally useful. For example, a random generator
by implemented by the Math class (i.e., Math.random).
Do not
abuse the power of class methods. Most
of the time, methods should be instance methods. That is, methods should be usually declared
without static.