Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do generic classes share static members? [duplicate]

I would like to ask about generic classes. What happens when I create two object instance from a generic class. Do they share every static members, or both have it's own static members?

So for example:

public A<?>(){
    public static Integer member = 0;
}

A<Integer> integer = new A<Integer>();
A<String> string = new A<String>();

Do both Integer and String have the same reference behind member?

like image 898
Quirin Avatar asked Jun 05 '13 21:06

Quirin


People also ask

Are static variables shared between classes?

Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Can generics be used with static methods?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

Can static variables be generic?

Using generics, type parameters are not allowed to be static. As static variable is shared among object so compiler can not determine which type to used. Consider the following example if static type parameters were allowed.

Can generic class inherit?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.


1 Answers

public class A<T>{
    public static Integer member = 0;

    public static void main(String[] args)
    {
      A<Integer> integer = new A<Integer>();
      A<String> string = new A<String>();

      integer.member++;
      System.out.println(string.member);
    }
}

Output

1

So, yes the two instances share the same member variable.

like image 116
Petros Tsialiamanis Avatar answered Sep 21 '22 05:09

Petros Tsialiamanis