通过Java中的对象引用访问静态变量 [英] Accessing a static variable via an object reference in Java

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

问题描述

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

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

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

    public String getX() {
        return this.x;                 // Case #1
    }

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

推荐答案

通常,每个人都可以访问公共变量,而只能从该类的当前实例内部访问私有变量.在您的示例中,您可以从main方法访问x变量,因为该方法在Static类之内.

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天全站免登陆