简体   繁体   中英

Why I am getting package not found error?

I have created two java files A.java and B.java . Both classes are in same folder testjava .

Code in A.java

package pkg;

public class A{
    int data;
    public void printer(){
        System.out.println("I'm in A");
    }
}

Code in B.java

package mypkg;
import pkg.*;

public class B{
    void printer(){
        System.out.println("I'm in B");
    }
    public static void main(String[] args){
        A obj = new A();
        obj.printer();      
    }
}

To compile first file I used: javac -d . A.java javac -d . A.java which compiled with no errors and created A.class in ./pkg folder
To compile second file I am using javac -cp "./pkg" B.java which gives me the following errors:错误图像

My directory structure after compilation of A.java :A.java编译后

What should include as my classpath ? I have read and tried other StackOverflow questions on the same topic but couldn't solve my problem.

无法从类型 A 对非静态方法printer() 进行静态引用。您正在从静态区域调用实例方法“printer()”。

Assuming your project directory looks like this:

project| tree
.
├── mypkg
│   └── B.java
└── pkg
    └── A.java

you should compile A like this:

javac pkg/A.java

and B with

javac mypkg/B.java

you should do this from the project directory. After you compile, the directory structure looks like this:

project| tree
.
├── mypkg
│   ├── B.class
│   └── B.java
└── pkg
    ├── A.class
    └── A.java

BTW, you have a syntax error in your code, should be obj.printer(); instead of A.printer(); .

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