Access static variable from object in Java

2019-01-25 12:21发布

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);
  }   
}

标签: java scope
4条回答
Melony?
2楼-- · 2019-01-25 12:57

The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.

The instance object could always refers to static members as it belongs to class which global(shared) to its instances.

查看更多
Root(大扎)
3楼-- · 2019-01-25 13:03

static variables are otherwise called as class variables, because they are available to each object of that class.

As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.

查看更多
Juvenile、少年°
4楼-- · 2019-01-25 13:21

It is not best practice to reference a static variable in that way.

However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.

This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.

查看更多
Summer. ? 凉城
5楼-- · 2019-01-25 13:22

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.

查看更多
登录 后发表回答