从Java中的对象访问静态变量 [英] Access static variable from object in Java

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

问题描述

为什么我们可以从Java中的对象访问静态变量,如下面的代码?

Why can we access a static variable from object in Java, like the code below?

public class Static {
  private static String x = "Static variable";

  public static void main(String[] args)
  {
    Static member = new Static();
    System.out.println(member.x);
  }   
}


推荐答案

一般来说,每个人都可以访问公共变量,私有变量只能从类的当前实例中访问。在您的示例中,您可以从 main 方法访问 x 变量,因为该方法在Static中class。

Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.

如果你想知道为什么你可以从另一个静态类实例访问它而不是你当前所在的实例(通常不是允许私有变量),这只是因为静态变量不是基于每个实例存在,而是基于每个类。这意味着可以从 A 的所有实例访问 A 的相同静态变量。

If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.

如果这不是在这种情况下,没有人能够访问私有静态变量,因为它不属于一个实例,但它们都属于。

If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.

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

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