Java ‘static’ keyword

Athiththan Kathirgamasegaran
2 min readFeb 14, 2019

--

This is a short brief introduction to the most valuable and more confusing keyword in Java

The keyword 'static' indicates that the particular member belongs to a type itself, rather than to an instance of that type

Simply, only one instance of that particular static member is created and shared across all instances of that particular class. The 'static' keyword can be applied to variables, methods, and nested classes.

'static' fields

If a field is declared with static keyword, then exactly a single copy of that field is generated/created and shared across all instances of that particular class.

If a field is not declared with the static keyword, then it is annotated as an instance variable; which resides in each new object of its respective class with its own distinct copy of itself

example

Lets assume that we are working on a smartphone company, in which we produce a number of smartphones and deliver it to the customers. Each new object (smartphone) instantiated from the following ‘SmartPhone’ blueprint (class) will have its own distinct copy of instance variables (modelNumber, battery).

Now we have a requirement to hold the count instantiated ‘SmartPhone’ objects. So in-order to do that we need to have a variable which can be shared across all instances such that they can access it and increment it upon their initialization. This is where ‘static’ variables comes in …

‘static’ methods

Similar to ‘static’ fields, static methods also belongs to a class instead of an object. So they can be called without creating any object related to a class in which they reside.

‘static’ methods are generally used to perform an operation which is not dependent upon instance creation. If there is a code that is supposed to be shared across all instances of a particular class, then declare the code fragment in a ‘static’ method.

‘static’ methods are widely used to create utility and or helper classes, so that they can be obtained without creating any new instances (objects) of those classes.

--

--

Athiththan Kathirgamasegaran
Athiththan Kathirgamasegaran

Written by Athiththan Kathirgamasegaran

@athiththan11 | GH:athiththan11 | Site Reliability Engineer@WSO2

No responses yet