How do I run a Java class in a package?

后端 未结 5 1776
眼角桃花
眼角桃花 2020-11-28 11:37

I have two java classes as follows

App1 without a package:

class App1 {
    public static void main(String[] args) {
        System.out.         


        
5条回答
  •  独厮守ぢ
    2020-11-28 12:02

    You create a new directory. This is the directory containing your work, and is not the start of your packages.

    For instance, I create folder /terri to start.

    I then create the folder structure /clarie/andrea under it. My package is going to be called claire.andrea in this example. Normal package names start with com and then a company name or something like that (or java for standard java packages, so don't use that: like java.lang.*).

    In the andrea folder, I create a java file called Saluton.java with the class Saluton (which just print hello). The class name and the filename must match.

    To compile, from the terri/ folder: javac .\claire\andrea\Saluton.java This will create a Saluton.class in the \terri\claire\andrea\Saluton.class

    To run: (again from /terri), I do: java -cp . claire.andrea.Saluton Which says, use class path from my current directory.
    My main program is in the package claire.andrea and the Class name is Saluton.

    Here's the run: \terri java -cp . claire.andrea.Saluton

    "Hello World".

    To sum it up, the package name much match the underlying directory structure. The file (if it references a package) must live inside the directory stucture it is refering. If I compile Saluton.java in /terri with package claire.andrea I have not found a way to run it, it does compile fine.

    Also, the filename for the class must match the public class in that file.

    To run, package.Class. In general, packages are not capitalized and Classes are.

提交回复
热议问题