Static fields in Generics

If you have used static fields before you would be aware that no matter how many instances of a class you create, you will always end up sharing the static field among all instances and there will be only 1 value. Changing the static value would effect and reflect the new value for all instances of the class as shown below.

image

 

image

CWindowssystem32cmd.exe

In the example, I am incrementing the static variable count in the constructor of the person class. So every time a new instance of person class is created the counter increases by 1. From the output shown below you would notice that for the person zeeshan, initially the counter was 1, when we created an instance of Paul Person, counter incremented to 2. As a result the counter value got effected for both persons as shown in the output. All this demonstrate is that static fields are shared among all instances of the class.

This is not the behavior you would expect in a generic class. If you have a Generic class T, than each closed type would have its own static variable. Basically a Person<Employee> and Person<Customer> would not be sharing the same static field. Let's look at an example of that.

image

image

CWindowssystem32cmd.exe

In the person class, I am printing the type of closed generic class I am in, the static count field and the instance Name field. Notice that the count is not showing 4 at any point, even though we have instantiated 4 instances of Person class. The reason is we have only instantiated only 2 instances of closed generic type. meaning we have two closed types one is Person<Employee> and second is Person<Customer> and each of those closed types have their own static field variables.

No Comments