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

}

}

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值