main方法中的静态方法调用局部变量

为什么在main方法中用类的静态方法调用main方法中创建的局部变量(非static)是可以的?不是说静态方法只能调用static变量吗?求大佬解答

public class Identity {
    String num = "";
    
    public static int countDigits(String id) {
        return id.length();
    }
    
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        String string = "";
        
        System.out.println("请输入你的身份证号:");
        
        countDigits(string);
        
        String id = scanner.nextLine();
        System.out.println("原来你的身份证号码是" + countDigits(id) + "位数字啊");
    }
}

 

在哪里?没看见

static 虽然是 class 的小弟,但是不必专属于 class 的分身(instance 或者 object),其他人都可以使唤它,所以他是大众服务生。static A君 和 static B君 是兄弟关系,它们可以在一起打球,传来传去。但是 static 不可以使唤 non static 资料。所以象 main君, 就不可以用 non static 群,用了就会显示  “non-static method cannot be referenced from a static context”。例如,我用你的例子 ==》

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        String string = "";  // 地方的 static 丫鬟

        System.out.println("请输入你的身份证号:");
        
        num = string; // <== java: non-static variable num cannot be referenced from a static context

        countDigits(string);

        String id = scanner.nextLine();
        System.out.println("原来你的身份证号码是" + countDigits(id) + "位数字啊");
    }

 

non static 群属于私人领域,但它可以使唤 static 群--大众服务生。你要用分身(instance 或者 object)去呼唤 class 里面的 public 群。

 

能调用但是不能创建,从生命周期的角度考虑就可以理解这个问题