Accessing a static variable via an object reference in Java

前端 未结 6 1430
耶瑟儿~
耶瑟儿~ 2020-11-29 11:26

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 variab         


        
6条回答
  •  忘掉有多难
    2020-11-29 12:06

    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.

提交回复
热议问题