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

查看:18
本文介绍了通过 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 变量,因为该方法位于静态类中.

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