0

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 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.

manusrao
  • 40
  • 7
  • 3
    Please no images of text, code or error messages. – akarnokd Jun 23 '22 at 07:45
  • 1
    The package path like a.b.c relates to a directory path a/b/c/. So you have to create subdirectories pkg and mypkig. – Joop Eggen Jun 23 '22 at 07:46
  • 1
    When you compile with `-d .`, the directory `.` is the target and hence, the classpath for subsequent operations. So don’t use `-cp "./pkg"` but `-cp .` Just being consistent helps a lot… – Holger Jun 23 '22 at 07:51

2 Answers2

0

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.

Ashutosh
  • 49
  • 5
0

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

naimdjon
  • 3,162
  • 1
  • 20
  • 41