Home > Net >  I cannot import class of one file to another in a subfolder in Java using vscode
I cannot import class of one file to another in a subfolder in Java using vscode

Time:11-23

How can import a class in different directory in subfolders??

I am new in Java programming language and i want to use a class in other directory by importing their packages but i can't do it !!.

i have a class called Car.

package ir.tclas.clasor.models;

public class Car {
private String Models;
private String Name;
private String Color;
private Integer weigth;


public void setWeigth(Integer weigth) {
    if (weigth > 50)
        this.weigth = 45;
    else {
        this.weigth = weigth;
    }

}

public String getModels() {
    if (Models == null)
        Models = "NO_Name";
    return Models;
}


  public void horn() {
  System.out.println("Beeeeeep!!!");
  }
}

now i want import Car from MainApp

  package ir.tclas.clasor;

  import ir.tclas.clasor.models.Car;

  public class MainApp {
  public static void main(String[] args) {

    Car bmw = new Car();

    bmw.setName("BMW");
    bmw.setColor("Blue");
    bmw.setWeigth(55);

    bmw.horn();
    System.out.println(bmw.getName());
    System.out.println(bmw.getModels());
    System.out.println(bmw.getColor());
    System.out.println(bmw.getWeigth());
 }
}

this is my out put after run my code:

 PS E:\java_pj\001\demo> cd 
 "e:\java_pj\001\demo\src\main\java\ir\tclas\clasor\" ; if ($?) { 
 javac MainApp.java } ; if ($?) { java MainApp.java }
 MainApp.java:4: error: package ir.tclas.clasor.models does not exist
 import ir.tclas.clasor.models.Car;
                         ^    
 MainApp.java:9: error: cannot find symbol
    Car bmw = new Car();
    ^
 symbol:   class Car
 location: class MainApp
 MainApp.java:9: error: cannot find symbol
    Car bmw = new Car();
                  ^
 symbol:   class Car
 location: class MainApp
 3 errors

 PS E:\java_pj\001\demo\src\main\java\ir\tclas\clasor>

Can anyone tell me how to do it?

CodePudding user response:

Code Runner doesn't include packages when compiling .java files and that's why error occurs, you should manually change the command in Settings.json:

"code-runner.executorMap": {
    "java": "cd e:/java_pj/001/demo/src/main/java && javac ir/tclas/clasor/models/Car.java && javac ir/tclas/clasor/$fileName && java ir/tclas/clasor/$fileNameWithoutExt",       
}

enter image description here

OR you can directly disable the extension Code Runner and run your project by Java Extension. After adding getters and setters in Car.java, your code works well, and no errors are shown:

enter image description here

  • Related