• Post Reply Bookmark Topic Watch Topic
  • New Topic

7.1 A Generic Class is Shared by all its Invocations  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone please explain the statements in quotes below with examples? They are generics tutorial avilable at source:http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
7.1 A Generic Class is Shared by all its Invocations
"As consequence, the static variables and methods of a class are also shared among
all the instances. That is why it is illegal to refer to the type parameters of a type
declaration in a static method or initializer, or in the declaration or initializer of a static
variable."
TIA.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to the JavaRanch!

See the code:



You see here we have created three parameterized objects. We wont have
three different classes parameterized with String, Integer and Double.
There will be only class, shared by all the invocations.

Come to the next point:


That is why it is illegal to refer to the type parameters of a type
declaration in a static method or initializer, or in the declaration or initializer of a static
variable."



You know there is single copy of all the static members of the class, shared
by all the objects. Lets modify our MyType class:

class MyType<T> {
static T a; //Error
}

We get error because there will be only MyType class shared by all
invocations. If it was allowed then there must have each copy of the member
for all the types we invoke, like in our example for String, Integer and
Double and list would go long and long. That is why the type parameter
you have used for the class can't be used in the static context.

Although following is allowed:



Thanks,
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!