How do I run a Java class in a package?

后端 未结 5 1774
眼角桃花
眼角桃花 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 11:53

    If you put the source in an appropriate directory hierarchy matching the package name (D:\javaTest\java\java\package1\App1.java), and compile/run from the root of the hierarchy (D:\javaTest), you wouldn't have this problem:

    D:\javaTest>javac java\java\package1\App1.java
    
    D:\javaTest>java java.java.package1.App1
    App2 hello world...
    

    You can also compile using the -d option so that the classes are moved into such a directory hierarchy:

    javac -d . App2.java
    java java.java.package1.App2
    

    Note you shouldn't use a package name starting with java, and later versions of the JDK will throw a SecurityException. See this question for more information.

提交回复
热议问题