Java convention on reference to methods and variables

前端 未结 6 1177
一个人的身影
一个人的身影 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 17:13

    You are allowed to access static members either by using the class name notation or by accessing using an object. It is not recommended to use the object notation since it can be very confusing.

    public class TheClass {
        public static final staticValue = 10;
        public static void staticMethod() {
            System.out.println("Hello from static method");
        }
    
        public static void main(String ... args) {
            TheClass obj = null;
    
            // This is valid
            System.out.println(obj.staticValue);
            // And this too
            System.out.println(obj.staticMethod());
    
            // And this is also valid
            System.out.println(((TheClass)null).staticValue);
            // And this too
            System.out.println(((TheClass)null).staticMethod());
    
        }
    }
    

    It is much clearer if the static methods and variables are called with the class name notation.

提交回复
热议问题