package in .java file makes class file unuseable

前端 未结 4 1793
忘掉有多难
忘掉有多难 2021-01-22 16:41

It\'s been too long since I\'ve last done Java, and I can\'t remember why the following happens:

Given this file, created by a standard Maven project, as can be seen her

4条回答
  •  轮回少年
    2021-01-22 16:54

    One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class. In your case the package name is "com.mycompany.app" so the App.class (compiled App.java file) should reside in "com/mycompany/app" sub-directory. It doesn't matter where the source file is residing though. For example, I have copied your file and did the following:

    $ ls
    App.java
    $ javac App.java 
    $ ls
    App.class       App.java
    $ mkdir -p com/mycompany/app
    $ mv App.class com/mycompany/app/
    $ java com.mycompany.app.App
    Hello World!
    $ 
    

    Please read Wikipedia page about Java Packages for more information. You can also take a look at these links:

    • The Java packages tutorial
    • Java packages tutorial
    • Oracle's notes on packages

    Good luck!

提交回复
热议问题