How to compile and run a java class with a package

2020-04-23 07:37发布

问题:

I have a class called MyClass in the file MyClass.java file (code mentioned below)

package myclass;

class MyClass {
  public int add (int a, int b){
    return a+b;   
  }

  public static void main(String args[]) {
    MyClass obj = new MyClass();
    System.out.println(oobj.add(2, 3));
  }
}

I am compiling the class with

javac MyClass.java

But I am trying to run the class using

java MyClass

or

java myclass.MyClass

I am getting the Error

Error: Could not find or load main class MyClass

But, I am able to run this program if I omit out the package name. where am I going wrong?

回答1:

Make sure that you are inside the parent directory of the package folder (the folder in which your compiled class file is), and execute the following command:

java myclass.MyClass

Below is an example file structure:

bin
    -> myclass
        -> MyClass.class

In the example structure above, you would have to execute the command from the "bin" directory.

Also, define the class as public and recompile the java source file.



回答2:

I ran into this too. It's very frustrating for someone from other languages. The key here is, the java file has to be in the right directory depending on the package declaration.

if the java file Test1.java starts with

package com.xyz.tests;

Then the java file Test1.java needs to be in directory com/xyz/tests

You can compile and run as

javac com/xyz/tests/Test1.java
java com/xyz/tests/Test1

Good luck.



回答3:

You Need To Compile The Class using :

javac -d ./myclass  


回答4:

I get my example to run by

java <package>.<class>

From parent directory of package