Java method and variable reference convention

Section 10.2 of the Java conventions recommends using objects instead of names instead of names instead of static variables or methods, i.e. MyClass.variable1or MyClass.methodName1()instead

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

There is no explanation for this, although I suspect that this has something to do with memory usage. It would be great if anyone could explain this.

+5
source share
6 answers

I assume that you mean "for static methods and variables."

, , , . , , .

, ,

MyClass.methodName1()

, Obj1.

obj1.variable1; // note the "o" instead of "O", please do follow conventions

, , 1 .

+8

, Class Name.

,

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

,

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.

+3

public static. / , , className.methodName() className.variableName

" " , ,

0

, public static method public static variable , . , , / / . , , .

0

, . , .

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

    }
}

, .

0

a static variable belongs to the class, and not to the object (instance). A static variable can be accessed directly by class name and does not need any object. it saves space by not having variables for the same data for each class.

Syntax : <class-name>.<variable-name>

public class AA{

 static int a =10;


}

You may call

System.out.println(AA.a);
System.out.println(aObject.a);

There are no differences between the two calls, but maintain a coding convention to save more readbale

-1
source

All Articles