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
?
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.
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.
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.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With