Java Reference
In-Depth Information
MemberAccessTest.java:9: hour has private access in Time1
time.hour = 7; // error: hour has private access in Time1
^
MemberAccessTest.java:10: minute has private access in Time1
time.minute = 15; // error: minute has private access in Time1
^
MemberAccessTest.java:11: second has private access in Time1
time.second = 30; // error: second has private access in Time1
^
3 errors
Fig. 8.3
|
Private members of class
Time1
are not accessible. (Part 2 of 2.)
Common Programming Error 8.1
An attempt by a method that's not a member of a class to access a
private
member of that
class generates a compilation error.
this
Reference
Every object can access a
reference to itself
with keyword
this
(sometimes called the
this
reference
). When an instance method is called for a particular object, the method's body
implicitly
uses keyword
this
to refer to the object's instance variables and other methods.
This enables the class's code to know which object should be manipulated. As you'll see in
Fig. 8.4, you can also use keyword
this
explicitly
in an instance method's body.
Section 8.5 shows another interesting use of keyword
this
. Section 8.11 explains why
keyword
this
cannot be used in a
static
method.
We now demonstrate implicit and explicit use of the
this
reference (Fig. 8.4). This
example is the first in which we declare
two
classes in one file—class
ThisTest
is declared
in lines 4-11, and class
SimpleTime
in lines 14-47. We do this to demonstrate that when
you compile a
.java
file containing more than one class, the compiler produces a separate
class file with the
.class
extension for every compiled class. In this case, two separate files
are produced—
SimpleTime.class
and
ThisTest.class
. When one source-code (
.java
)
file contains multiple class declarations, the compiler places both class files for those classes
in the
same
directory. Note also in Fig. 8.4 that only class
ThisTest
is declared
public
. A
source-code file can contain only
one
public
class—otherwise, a compilation error occurs.
Non-
public
classes
can be used only by other classes in the
same package
. So, in this
example, class
SimpleTime
can be used only by class
ThisTest
.
1
// Fig. 8.4: ThisTest.java
2
// this used implicitly and explicitly to refer to members of an object.
3
4
public class
ThisTest
5
{
6
public static void
main(String[] args)
7
{
Fig. 8.4
|
this
used implicitly and explicitly to refer to members of an object. (Part 1 of 2.)