What is the purpose of static modifier?

StaticĀ modifier is commonly used in all programming languages. There are two distinct reasons for using the static modifier whether its C, Java, C#, PHP or Ruby –

  1. To access the class members without instantiating the object.

eg:

public class CutGrass{

public static void CleanMower(){

}

}

var endTheJob = CutGrass.CleanMower();

2. To restrict the representation of a concept as a single instance in memory. i.e not allowing it to be copied to different memory locations as various objects are instantiated from the class. A good example is the main method which is the point of entry to the program for most of the programming languages. Main method is always prefixed with static modifier so that its representation exists in only once place in memory and it cannot be copied.

eg:

static void Main(String[] args){}

 

Add a Comment

Your email address will not be published. Required fields are marked *