Reputation: 55
I am running the following Dog Java code. It can be compiled. However, in order to run it, I had to modify the code to comment out the line (package chap03). It was a code from a textbook. How do I pass the code to run with the package command?
package chap03;
public class Dog {
String name;
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.bark();
dog1.name = "Bart";
Dog[] myDogs = new Dog[3];
myDogs[0] = new Dog();
myDogs[1] = new Dog();
myDogs[2] = dog1;
myDogs[0].name = "Fred";
myDogs[1].name = "Marge";
System.out.print("last don't name is ");
System.out.println(myDogs[2].name);
int x = 0;
while (x < myDogs.length) {
myDogs[x].bark();
x = x + 1;
}
}
public void bark() {
System.out.println(name + " says Ruff!");
}
public void eat() {
}
public void chaseCat() {
}
}
Upvotes: 0
Views: 815
Reputation: 299078
To compile a program with a package, place it in a directory hierarchy that corresponds to the package, i.e. package foo.bar
corresponds to folders foo/bar
. Compile from the root (i.e. from the folder that contains the foo folder).
The output will also be stored in directories, so again, you need to go to the root folder of the hierarchy and run the class as
java foo.bar.YourClass
You might also consult the Packages Trail of the Java tutorial.
Upvotes: 4