Java convention on reference to methods and variables

前端 未结 6 1093
一个人的身影
一个人的身影 2021-01-18 16:19

Section 10.2 of Java conventions recommends using class names instead of objects to use static variables or methods, i.e. MyClass.variable1 or MyClass.met

6条回答
  •  [愿得一人]
    2021-01-18 16:59

    If you use object for static variable access then compiler will replace it with Class Name only.

    So

    MyClass Obj1 = new MyClass();    
    Obj1.variable1;
    Obj1.methodName1();
    

    It is same as

    MyClass.variable1;
    MyClass.methodName1();
    

    Now Why to differentiate? Answer is - It is for better reading If someone see method being called on Class then he immediately come to know that it is static method. Also it prevents generation of one additional object to access the method.

提交回复
热议问题