Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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!