Methods and attributes can be static. In Object Oriented Programming, static refers to being object-independent, i.e. a static method or attribute does not require an object to be instantiated for it to work.
Another way to look at it is that normal (instance) methods and attributes are unique to the instance/object, while their static counterparts are shared by all instances of the class.
Limitations
These limitations are on static methods, specifically:
- Static methods can only call other static methods. It doesn’t make sense for a static method to be able to call an instance method, because then we need to create an instance, which defeats the purpose of having a static method.
- Static methods can only access static data, i.e. variables with the static identifier, for the same reason.
- Static methods cannot refer to referential Java Keywords such as
this
orsuper
.
Use cases
Static Variables
- For keeping a ‘total’ of something, like a total count of objects instantiated\
Static Methods
- Anytime a class doesn’t really need to create an object
- Java’s
Math
library uses mostly static methods, likesin()
,abs()
etc. as there is no need to create a Math object