Java中的静态变量和方法的范围 [英] Scope of static variable and methods in Java

查看:85
本文介绍了Java中的静态变量和方法的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在Java中使用静态方法有些怀疑。
我读了很多地方静态变量是独立于实例的所以是全局的。

I have some doubts about usage of static method in Java. I read many places static variables are instance independent so be comes global.

public class ThirdClass {
    public static var = "Java";
}

public class Second {
    public static void main(String[] args) {
        ThirdClass ob1 = new ThirdClass();
        System.out.println(ob1.var);   // prints Java
        ob1.var="Ruby";
        ThirdClass ob2 = new ThirdClass();
        System.out.println(ob2.var);   // prints Ruby
    }
}

public class First {
    public static void main(String[] args) {
        ThirdClass ob3 = new ThirdClass();
        System.out.println(ob1.var);   // prints Java again!!!
    }
}

正如您在第二类中看到的多个ThirdClass共享实例变量var的相同实例。但是First类中的一个单独的实例不能访问最终值Ruby,而是显示原始的Java。这意味着静态变量不是全局变量,而只是全局到单个执行!!!

As you see in second class multiple instance of ThirdClass sharing same instance of variable var. But a separate instance in class First don't access the final value "Ruby" but show original "Java". It means the static variable are NOT global variable but only global to single execution!!!

与实例变量相比,还创建静态变量资源密集型吗?

Also do is creating static variable resource intensive compared to instance variable?

请建议。

推荐答案


这意味着静态变量不是全局变量,而只是全局到单个执行!!!

It means the static variable are NOT global variable but only global to single execution!!!

当然它们是。 未保存到某种存储(如硬盘)的所有变量不会在程序的不同执行之间保留其值。

Of course they are. All variables that are not persisted to some kind of storage (like the hard disk) do not retain their values between distinct executions of the program.

这篇关于Java中的静态变量和方法的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆