Hello all. I'm making my way through 'Head First
Java' and have encountered what seems to be a contradiction... Early on (on page 7) the book emphasizes that code structure in Java requires that a source file hold one and only one class definition. Later in the book (pg. 73) there is an example to demonstrate instance variables. I typed the code from pg. 73 into a source file and, just to see what would happen, put both class Dog and class DogTestDrive in the same source file (named DogTestDrive.java) The file compiled and ran successfully. What should I make of this apparent contradiction to the 'one class per source file' rule?? I've included the code below. It compiles successfully when class Dog and class DogTestDrive are in separate files and also when both classes are in the same file <DogTestDrive.java> Thanks in advance for your help.
class Dog {
int size;
String name;
void bark() {
if (size > 60) {
System.out.println("Wooof! Wooof!");
} else if (size > 14) {
System.out.println("Ruff! Ruff!");
} else {
System.out.println("Yip! Yip!");
}
}
}
class DogTestDrive {
public static void main (String[] args) {
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
Dog three = new Dog();
three.size = 35;
one.bark();
two.bark();
three.bark();
}
}
_ _ _ _ _ _
Output is:
Woof! Woof!
Yip! Yip!
Ruff! Ruff!