Home > database >  Why I am getting package not found error?
Why I am getting package not found error?

Time:06-23

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();
        A.printer();        
    }
}

To compile first file I used: 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: Error Image

My directory structure after compilation of A.java: After A.java compilation

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

CodePudding user response:

Cannot make a static reference to the non-static method printer() from the type A. You are calling the instance method "printer()" from the static area.

CodePudding user response:

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();.

  • Related