Java Reference
In-Depth Information
Access specifier, which can be public, private, or protected; or the access
specifier can be omitted, giving the field the default access.
■■
Data type.
■■
Name, which is any valid identifier that is followed by a semicolon.
■■
Access specifiers are discussed in detail in Chapter 7, “Advanced Java Lan-
guage Concepts.” Until then, we will use public access for fields and methods.
Specifying public allows access to the field or method from any other object.
The following Employee class has five fields: name, address, number, SSN,
and salary. When an Employee object is instantiated in memory, memory will
be allocated for each of these five fields.
public class Employee
{
public String name; //First and last name
public String address; //Mailing address
public int number; //Employee number
public int SSN; //Social Security number
public double salary; //Employee's salary
}
Keep in mind that a class describes what an object looks like. The
Employee class is being used to describe employees of a company in the
context of paying them weekly. The fields that appear in the Employee
class represent information about an employee that is needed to compute
his or her pay.
For example, an employee has a name and address, so the Employee class
has a name field and an address field. An important piece of information
in our example is the salary field used to represent the employee's salary.
Employees have other attributes that may not be relevant in our situation.
Suppose, for example that every employee has a manager or supervisor.
The Employee class does not contain a field for this information. However,
in computing someone's pay, his or her supervisor is probably not relevant.
This Employee class might look quite different if it were going to be used
for other purposes besides paying employees.
Adding Methods to a Class
Behaviors of an object become methods in the corresponding class. A method
within a class typically consists of the following:
Access specifier
■■
Return value
■■
Search WWH ::




Custom Search