通过 Java 中的对象引用访问静态变量

编程入门 行业动态 更新时间:2024-10-24 10:16:35
本文介绍了通过 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 01:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/674888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   静态   对象   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!