LightSpurs 2021-01-24 00:08 采纳率: 0%
浏览 23

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) + "位数字啊");
    }
}
  • 写回答

2条回答 默认 最新

  • 无厘头编程 2021-01-24 06:38
    关注

    在哪里?没看见

    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 群。

     

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?