Java Reference
In-Depth Information
3.9 How to Organize Java Files
In the previous section, we dealt with four classes— LinkedList , Node , NodeData , and LinkedListTest —and noted
that in order to store them in one file (as Program P3.4) we had to drop the word public from all but LinkedListTest .
Here, we recap some of our previous comments and explain how each class may be stored in its own file.
We can store the LinkedListTest class in a file, which must be called LinkedListTest.java . Remember that a
public class x must be stored in a file called x.java . We can store the other classes in the same file provided we write
the class header as class xxx rather than public class xxx .
However, in order for these classes to be usable by other classes, we will organize them differently. We will
declare the NodeData class as public and store it in a file by itself. The file must be called NodeData.java and, so far,
will contain the following:
public class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int compareTo(NodeData nd) {
if (this.num == nd.num) return 0;
if (this.num < nd.num) return -1;
return 1;
}
public String toString() {
return num + " ";
//" " needed to convert num to a string; may also use "" (empty string)
}
} //end class NodeData
We will declare the LinkedList class as public and store it in a file called LinkedList.java . Since the Node class
is used only by the LinkedList class, we will omit the word public and store it in the same file, which, so far, will
contain the following:
public class LinkedList {
Node head = null;
public boolean empty() {
return head == null;
}
public void addHead(NodeData nd) {
Node p = new Node(nd);
p.next = head;
head = p;
}
 
Search WWH ::




Custom Search