java - When to use static method and field? -
i know static is, not sure when use it.
static variable: used constant fields. there tens of constants in class, using static constants can save lots of memory. there other typical use cases?
static method: use when make class algorithms. example, class provides different sorting algorithms. against oop design? think better maintain way rather implementing sorting algorithms inside each class needs use them. wrong? use cases?
also, there performance difference between using static , non-static fields/methods?
you describing cases you've used static, doesn't quite explain fundamentally why use static vs non-static - more keywords constants , utility methods.
when not static (instance), means there instance of each instance of class. each 1 can change independently.
when static, means there 1 copy of instances of class, changing location affects others.
static variables/methods typically use less memory because there 1 copy of them, regardless of how many instances of class have. statics, when used appropriately, fine in object oriented design.
if have method/variable need 1 instance of (e.g. constant or utility method), make static. understand though making method static means cannot overridden. if have method want override in subclass, don't make static.
the general rule of thumb - if need 1 copy of it, make static. if need copy per instance, make non static.
Comments
Post a Comment