简体   繁体   中英

How to import class of one file to another in a subfolder in Java using vscode

import mytest.Mypckg;

public class Learn {
  public static void main(String[] args) {
    System.out.println("Hello World");
    Mypckg.show();
  }
}
package mytest;
public class Mypckg {
  public static void show(){
    System.out.println("Good Moring");
  }
}

Both file are in same subfolder name mytest but when I try to run main file => Learn, I am getting an error "Learn.java:2: error: cannot find symbolimport mytest.Mypckg;". I have also tried by removing import mytest.Mypckg from Learn file as both are having same package but when I compile I am getting an error as "cannot find symbol Mypckg".

I am assuming that both the files are in the package/folder named mytest and your code seems to miss this line added below

package mytest;//added line
//import mytest.Mypckg;

public class Learn {
  public static void main(String[] args) {
    System.out.println("Hello World");
    Mypckg.show();
  }
}

you are right in one case that I have not mentioned package mytest in main file (Learn.java). that's my bad but in my computer when I mentioned package mytest in both file then also I was getting an error like "cannot find symbol import mytest.Mypckg;" 在此处输入图片说明

Finally I found the solution. The actual problem was I was using compiling method inside the subfolder mytest. Infact I tried to compile the file by going outside the subfolder to get the path for mytest folder. But the main culprit was something else.I was not using the class path (ie -cp) in my compilation code. So to compile the package file in vscode we have to go to parent folder & type the following code.

javac -cp . mytest/Learn.java // compiler code with file path 

And also to run the file we have to use

java mytest.Learn     // mytest is a subfolder (package folder) and learn is a main file

Here Below I have attached the image for better clarification for my fellow colleagues. I hope my answer will help someone who wants to compile java code with package in vscode在此处输入图片说明

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