Why is it better to use class name instead of objects to access class methods or variables in Java? -
i reading code conventions java http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#587.
in that, have mentioned should avoid use of objects access class variable or method , should use class name instead.
avoid using object access class (static) variable or method. use class name instead. example:
classmethod(); //ok aclass.classmethod(); //ok anobject.classmethod(); //avoid!
is there particular reason in terms or performance or else?
by class variables assume mean static variables.
the use of static variables/methods through instance variables should avoided because it's confusing reader. since can use instances access instance variables, reading code calls static methods through instance can confuse reader what's going on.
image case, thread.sleep
, static method:
thread.sleep(1000);
since method static , calling through class name, it's intuitive reader deduce effect put current thread sleep.
now if did this:
thread t = new thread(...); t.sleep(1000);
now thread put sleep? current 1 "obviously". not knowing how sleep works might think child thread somehow put sleep.
Comments
Post a Comment