Java Reference
In-Depth Information
If the comments have been removed from EmployeeApp, the line number 10 in the third line of the message
will be 7. Because displayName's access modifier is now
private
, only methods within Employee can access
displayName. In other words, EmployeeApp cannot use the private displayName method because EmployeeApp
is a different class.
Notice that in the Navigation tree RAD has flagged EmployeeApp, the package, and the project as having an error.
6.
Click on the Content pane's EmployeeApp.java tab to display the source code.
Notice that RAD has also flagged line 10 as in error.
We will change EmployeeApp and Employee so that the displayName method is called from within Employee not
EmployeeApp.
7.
In EmployeeApp, select the entire statement on line 10:
emp.displayName();
8.
Click
Edit
and
Cut
to remove the line of code.
9.
Redisplay the source code for Employee.java (i.e., Click the Content pane Employee tab).
10. Move your cursor to the end of line 8 and press Enter to insert a blank line after
empName = name;
11.
Click
Edit
and then
Paste
to place
emp.displayName();
on line 9.
Notice that the line is flagged as an error and emp has a red squiggly line beneath it.
Because we are trying to run displayName from within the Employee class, we can't refer to the variable emp
that was created in EmployeeApp. We must specify that we want to execute the displayName method within
this
(i.e., the Employee) object/class.
12.
On line 9, replace
emp
with
this
so that the statement looks like the following:
this
.displayName();
The executable code should look like the following:
package
myFirstPackage;
public class
Employee {
String empName =
new
String();
public
Employee(String name) {
empName = name;
this
.displayName();
}
private void
displayName() {
System.out.println(empName);
}
}
There is a shorter and simpler syntax for identifying/running a method within the same class: simply specify
the method name, parentheses, and a semicolon as in the following:
displayName();
Are you wondering, “How/why does this work?” Well, because an object is not specified (i.e., emp in
emp
.displayName( ); is not specified), the JVM assumes that the displayName method is in the same class (Employee).
However, because this seems like “magic” we will continue to use the token
this
for clarity.