简体   繁体   中英

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

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?

Disable 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:

在此处输入图像描述

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