我是否跪着为不同的文件导入库?

Do I kneed to import libraries for different files?

假设我有两个文件:

// File Main.java
import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       // Scanner stuff here...
       Food.fries();
   }
}
// File Food.java
public class Food {
    public static void fries() {
        System.out.println("Some fries...")
        // Can I do Scanner stuff here without importing?
    }
}

我知道如果 classes 在同一个文件中,我不需要为每个 class 导入。现在,如果我想在 class Food(单独的文件)中使用 Scanner 进行操作,是否需要再次导入 Scanner?

您可以再次导入扫描仪 class 以便能够在 Food class 中使用它。 但是,我建议您将 sc 变量设置为静态变量和全局变量 (Scanner sc = new Scanner(System.in);) 因此,在您的主要 class 中,您必须创建如下变量:

public class Main {

   public static Scanner sc = new Scanner(System.in);

   public static void main(String[] args) {

       // Scanner stuff here...
       Food.fries();
   }
}

在你的食物里面class:

public static void fries() {
    System.out.println("Some fries...Give me a number:");
    Main.sc.nextInt();
}

Those examples work if you have the files in the same package.

现在,你在这里必须小心,因为如果你的 Main class 在另一个 java 包(或文件夹)中,那么你将必须导入 Main class 或者您可以使用静态导入。您可以使用它来避免使用语法 Classname.your_static_method()。例如,您的 Main class:

import java.util.Scanner;
import static yourpackagename.Food.fries;

public class Main {

   public static Scanner sc = new Scanner(System.in);
   public static void main(String[] args) {

       // Scanner stuff here...
       fries();
   }
}

As you can see now, I used a static import to use the fries() method which you have in the another class. So inside the main, you can call the method with the simple name, and not using the syntax Classname.static_method()

在 Food class 中,您可以对 Scanner 对象执行相同的操作 (sc):

import static yourpackagename.Main.sc;

public class Food {
        public static void fries() {
            System.out.println("Some fries...Give me a number:")
            sc.nextInt();
        }
}

Those examples work for files in the same package or in separate ones. You only have to do the import correctly.

现在,如果您不想使用静态导入并且文件或 classes 在单独的包中,您将必须像往常一样导入 class 并使用语法: Classname.static_methodorvariable()

import java.util.Scanner;
import thepackgename.Food;

public class Main {

   public static Scanner sc = new Scanner(System.in);
   public static void main(String[] args) {

       // Scanner stuff here...
       Food.fries();
   }
}

食物class:

import thepackagename.Main;

public class Food {
        public static void fries() {
            System.out.println("Some fries...Give me a number:")
            Main.sc.nextInt();
        }
}