关于引用方法和变量的Java约定 [英] Java convention on reference to methods and variables
问题描述
Java约定第10.2节建议使用类名而不是对象来使用静态变量或方法,即 MyClass.variable1
或 MyClass.methodName1 )
而不是
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.
推荐答案
我想你的意思是对于静态方法和变量。
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.
原理是通过读
MyClass.methodName1()
<你知道这是一个静态方法,它不能使用或更改你的 Obj1
实例。
如果你写
obj1.variable1; // note the "o" instead of "O", please do follow conventions
读取您的源代码以知道variable1是否为静态。
then the reader has to read your source code to know if variable1 is static or not.
这篇关于关于引用方法和变量的Java约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!