Java Reference
In-Depth Information
The following will be printed:
Name of part: Air Filter
Price: $8.75
2.7 How to Name Your Java Files
If our program consists of a single
public
class, Java requires us to store such a class in a file called
name of class
.
java
. So if the class is
Palindrome
, we must call the file
Palindrome.java
.
In the
Part
example, we must store the
Part
class in a file called
Part.java
, and we must store the
PartTest
class
in a file called
PartTest.java
. We could compile these classes with the following commands:
javac Part.java
javac PartTest.java
We could then run the test with this command:
java PartTest
Recall that this will execute
main
from the class
PartTest
. Note that it makes no sense to attempt something like
this:
java Part
If we do, Java will simply complain that there is no
main
method in the class
Part
.
We could, if we want, put both classes in one file. However, only one of the classes can be designated as
public
.
So, for example, we could leave class
PartTest
as it is and simply remove the word
public
from
public class Part
.
We could now put both classes in one file, which
must
be named
PartTest.java
since
PartTest
is the
public
class.
When we compile
PartTest.java
, Java will produce two files—
PartTest.class
and
Part.class
. We can then
run the test with this:
java PartTest
2.8 Working with Objects
So far, we have seen how to define a class and create objects from the class using a constructor. We have also seen how
to retrieve data from an object using accessor methods and how to change data in an object using mutator methods.
We now look at some issues that arise in working with objects.
2.8.1 Assigning an Object Variable to Another
An object variable (
p
, say) is declared using a class name (
Part
, say), like this:
Part p;
We emphasize again that
p
cannot hold an object but rather a pointer (or reference) to an object. The value of
p
is a memory address—the location at which a
Part
object is stored. Consider the following:
Part a = new Part("Air Filter", 8.75);
Part b = new Part("Ball Joint", 29.95);
Search WWH ::
Custom Search