Recent articles:
Popular archives:
Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can,
or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing
heavily in Java's future as a platform for platforms
Also see:
Discuss: Tim Bray on 'What Sun Should Do'
Read the whole series on object-oriented language basics:
Java's variables can be divided into three categories: fields, parameters, and local variables. I'll present fields here and leave an exploration of parameters and local variables for a later section that discusses methods.
A field is a variable declared in a class body that holds either part of an object's state (an instance field) or part of a class's state (a class field). Use the following Java syntax to declare a field in source code:
[ ( 'public' | 'private' | 'protected' ) ]
[ ( 'final' | 'volatile' ) ]
[ 'static' ] [ 'transient' ]
data_type field_name [ '=' expression ] ';'
A field declaration specifies the field's name, data type, optional expression (which initializes the field), access specifiers, and modifiers. Choose identifiers for the data type and name that are not reserved words. Consider this example:
class Employee
{
String name; // The employee's name.
double salary; // The employee's salary.
int jobID; // The employee's job identification code (e.g., accountant, payroll clerk, manager, and so on).
}
The Employee class declares three fields: name, salary, and jobID. When you create an Employee object, name eventually holds a reference to a String object that contains the employee's name. The salary field will hold the employee's salary, and jobID will hold an integer that identifies the employee's job category.
You can optionally declare a field with an access specifier keyword: public, private, or protected. The access specifier determines how accessible the field is to code in other classes. Access ranges from totally accessible
to totally inaccessible.
If you do not declare a field with an access specifier keyword, Java assigns the field a default access level, which makes the field accessible within its class and to all classes within the same package. (Think of packages as libraries of classes -- a concept I'll explore in a future article.) Any class not declared in the same package as the class that contains the field cannot access the field. Take a look at the following example: