Java Reference
In-Depth Information
if(newRate >= 0.0 && newRate <= 0.20)
{
commissionRate = (float) newRate;
}
else
{
System.out.println(“Rate must be between 0 and 20%”);
}
}
//Remainder of the SalesPerson class stays the same
}
Understanding Static Members
I have repeatedly mentioned that Java is strictly an object-oriented program-
ming language and that all code must appear within a class; however, there are
situations where it would be nice if a field or method did not have to be asso-
ciated with instances of a class. Sometimes a global-type field or method is
needed or would perhaps result in a better design.
The static keyword allows a field or method to not be associated with any
particular instance of a class. Instead, the field or method can be thought of as
global, and any other class can access the field or invoke the method without
requiring an instance of the class.
The important point to remember about static is that static members are
associated with the class, not particular instances of the class. In fact, a
static field or method can be accessed without any instances of the class
existing.
A static member of a class is often referred to as a class member because static
members are associated with the class and not with individual instances of the
class. Fields and methods that are not static are often referred to as instance
members because nonstatic fields and methods only exist within instances of
the class.
We have used static many times because it is a required attribute of the
main() method, as seen in the following ConstructorDemo program.
public class ConstructorDemo
{
public static void main(String [] args)
{
System.out.println(“Constructing a big screen TV”);
BigScreenTV tv = new BigScreenTV();
System.out.println(“Done constructing TV”);
}
}
Search WWH ::




Custom Search