java – Static field in generics / template


There is a Java generics class like:

public class MyClass<T> {
   static long myField=System.currentTimeMillis();


Two objects are created:

MyClass<String> var1=new MyClass<String>();
MyClass<Integer> var2=new MyClass<Integer>();

question: are var1.myField and var2.myField ?


And if it is a template in C ++ / C # – then will they be the same or not?


Answer: Yes, they are the same for Java

Your example is not the best one to demonstrate this. It is known that StringBuilder does not reference the same pool and creates a new object each time. Let's use it to validate the statement:

public class Clazz<T> {
    static StringBuilder myField= new StringBuilder("Test text");

    public static void main (String args[]) throws InterruptedException {
        Clazz<String> var1=new Clazz<String>();
        Clazz<Integer> var2=new Clazz<Integer>();
        // Одинаковые ли ссылки на объект?
        System.out.println(var1.myField == var2.myField); 
        // Одинаковы ли содержания объектов?



In C ++, as far as I understand, there is no direct analogue of the generic class. There are templates and they work somehow differently. I jotted down some code:

template <class T> class Test {
    public: static int count;

template <class T> int Test <T> ::count;

int main() {
    Test <int> a;
    Test <int> b;
    Test <double> c;
    a.count = 2;
    b.count = 1;
    c.count = 1;
    // Одинаковы ли ссылки?
    cout << (&a.count == &b.count) << endl;
    // Одинаковы ли содержания?
    cout << (a.count == b.count)<< endl;
    // Одинаковы ли ссылки?
    cout << (&a.count == &c.count) << endl;
    // Одинаковы ли содержания?
    cout << (a.count == c.count) << endl;

    return 0;

A static variable inside a template turns out to be the same for objects created with the same type ( int ) and different for different types. The output of this program is as follows:



There is no way to do research in C # (OS does not support), but I found a similar question on the English-language StackOverflow: Are static members of a generic class tied to the specific instance?

Things there don't seem to be very different from C ++.

A static variable is the same for all instances of the same type. Foo<int> and Foo<string> are two different types. This can be shown in the following example:

 // Результатом будет "False" Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>));

This can be found in the 1.6.5 paragraph of the C # Language Specification (for C # 3):


Scroll to Top