简体   繁体   中英

How to use the package directive?

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() {
    }
}

To compile a program with a package, place it in a directory hierarchy that corresponds to the package, ie package foo.bar corresponds to folders foo/bar . Compile from the root (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM