java中是否有所谓的全局变量? [英] is there anything called global variable in java

查看:264
本文介绍了java中是否有所谓的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章 Java中的全局变量,它描述了如何在全局变量中定义通过使用静态的Java $ /

  public class Example {
public static int a;
public static int b;
}

但同时在其他文章为什么Java中没有全局变量?这个问题相矛盾。
所以我的问题是什么是全局变量?
java是否支持全局变量?如果是,如何?
如果不是,为什么?
以及java全局变量(如果有的话)与c ++全局变量有何不同?

我们可以争辩说在java中没有全局关键字,但是您的示例可以像全局一样对待。



In大多数语言,你可以定义一个全局变量,问题是他们污染全局命名空间和名称冲突可能发生(如在PHP中)。在这方面,在java中没有全局变量,因为没有全局名称空间:变量总是在类中。



所以最主要的是:没有java中的显式全局在java中没有全局名称空间。这可以让你摆脱名称冲突和意外重写,这是件好事。



但是没有什么能够阻止你创建一个 Global 类, public static 字段。



请注意大多数人(包括我)会因为这样做而破坏你的双手。 :)

According to this post Global variables in Java it describes how to define a global variables in java by using static

 public class Example {
        public static int a;
        public static int b;
    }

But at same time in other post Why are there no global variables in Java? this question contradicts . So my question is what exactly is global variable ? Do java supports global variables ?if yes ,how? if no ,why? and how java global variables(if there are any) are different from c++ global variables?

解决方案

I think that we can argue that there is no global keyword in java but your example can be treated like a global.

In most languages where you can define a global variable the problem is that they pollute the global namespace and name clashes can occur (like in php). In this regard there are no globals in java since there is no global namespace: variables are always in a class.

So the main thing is: there is no explicit globan in java and there is no globan namespace in java. This frees you from name clashes and accidental overwrites which is a good thing.

But there is nothing stopping you from creating a Global class with a lot of public static fields in it.

Please note that most guys (including me) would break both of your hands for doing so. :)

这篇关于java中是否有所谓的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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