Java Reference
In-Depth Information
Suppose we create a part with this:
Part af = new Part("Air Filter", 8.75);
The expression
af.printPart()
would display the following:
Name of part: Air Filter
Price: $8.75
When
printPart
is called via
af
, the references in
printPart
to the fields
name
and
price
become references to
the fields of
af
. This is illustrated in Figure
2-4
.
name: Air Filter
725
af
price: 9.50
printPart()
System.out.printf("\nName of part: %s\n", name);
System.out.printf("Price: $%3.2f\n", price);
Figure 2-4.
name
and
price
refer to the fields of
af
2.5.2 Using a Static Method
We could, if we want, write
printPart
as a
static
method, which will be called with
p
as an
argument
in order to print
its fields. In this case, we will write the following:
public static void printPart(Part p) {
System.out.printf("\nName of part: %s\n", p.name);
System.out.printf("Price: $%3.2f\n", p.price);
}
The field names have to be qualified with the object variable
p
. Without
p
, we would have the case of a static
method referring to a non-static field, which is forbidden by Java.
If
c
is a
Part
object created in a user class, we will have to use the following to print its fields:
Part.printPart(c);
This is slightly more cumbersome than using the instance method, shown previously. By comparison, you can
use, for instance,
Character.isDigit(ch)
to access the static method
isDigit
in the standard Java class
Character
.
2.5.3 Using the toString() Method
The
toString
method returns a
String
and is special in Java. If we use an object variable in a context where a string is
needed, then Java will attempt to invoke
toString
from the class to which the object belongs. For example, suppose
we write the following, where
p
is a
Part
variable:
System.out.printf("%s", p);
Search WWH ::
Custom Search