Win a copy of Terraform in Action this week in the Cloud forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

7.1 A Generic Class is Shared by all its Invocations

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic