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.methodName1()
instead of
MyClass Obj1 = new MyClass();
Obj1.variable1;
Obj1.methodName1();
There is no explanation of the rationale behind this, although I suspect this has something to do with memory use. It would be great if someone could explain this.
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters.
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
Methods should be verbs in lowerCamelCase or a multi-word name that begins with a verb in lowercase; that is, with the first letter lowercase and the first letters of subsequent words in uppercase. Local variables, instance variables, and class variables are also written in lowerCamelCase .
is prefix should be used for boolean variables and methods. This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag.
I guess you mean "for static methods and variables".
There is no difference regarding memory, except of course if you create the instance just for calling the method. Conventions aren't for memory efficiency but for coder efficiency, which is directly related with the readability of the code.
The rationale is that by reading
MyClass.methodName1()
you know it's a static method and that it can't use or change your Obj1
instance.
And if you write
obj1.variable1; // note the "o" instead of "O", please do follow conventions
then the reader has to read your source code to know if variable1 is static or not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With