Java Reference
In-Depth Information
Accessing Fields and Methods
When you instantiate an object using the new keyword, memory is allocated
for each of the fields and methods in the class. You need a reference to the
object to access these fields and methods using the dot operator.
For example, the following statements declare an Employee object and
change the name field of the object:
Employee e = new Employee();
e.name = “Robert Smith”;
The operation e.name is the way to access the name field of the Employee
object that e refers to. Similarly, the following statement uses the dot operator
to invoke the mailCheck() method of this particular Employee object:
e.mailCheck();
Using the Dot Operator
Let's go through an example that demonstrates writing a class, creating
instances of that class, and using the dot operator to access the fields and
methods of the objects.
We have been discussing the Employee class throughout this chapter, so we
will begin by writing and compiling the Employee class. We will then write a
second class that uses the Employee class. Follow along with the subsequent
steps, which will help you to understand the process of using multiple classes
in a program.
Step 1: Write the Employee Class
Open Notepad (or the text editor of your choice) and type in the following
Employee class.
public class Employee
{
public String name;
public String address;
public int number;
public int SSN;
public double salary;
public void mailCheck()
{
System.out.println(“Mailing check to “
+ name + “\n” + address);
Search WWH ::




Custom Search