• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics for classes  RSS feed

 
Alan Blass
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I just want to clarify generics for classes.

Referring to http://docs.oracle.com/javase/tutorial/java/generics/types.html

Generics means all methods in class Box will return an Integer if their parameters are defined as T when the instantiation is
Box<Integer> integerBox = new Box<Integer>();

Are those Boxes only can contain Integers? Can I write

Box <Toys> toybox = new Box <> ();

To show that the Box only contain toys?

Please advise . Thanks
 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it on the compiler and see what happens.
 
Anuj Sharma R
Greenhorn
Posts: 28
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can if you are referring to Toys as a class here.
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Blass wrote:Can I write

Box <Toys> toybox = new Box <> ();

To show that the Box only contain toys?

Yes.
Before Generics you would have had to write the Box class as accepting and returning Object types and then cast the returned values to whichever type you were storing in your Box. With Generics, put simply, you tell the compiler what type you are putting into your Box and it provides type safety checks for objects you pass to the Box and silently casts the returned values from the Box to the correct type.
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Tony,
..and silently casts the returned values from the Box to the correct type.

Can you explain more about this? How it casts and when? Does it cast from Object to Toys ? I'm studying generics right now and your quote intrigued me.

Thank you
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics in Java use type erasure meaning that the generics information only exists at compile time ie the compilation process removes all generic type information. During compilation the generic types are replaced with either Object types or the Bound types if the generics are bounded and casts are added when assigning the generic type references returned from the class.

See http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My pleasure.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!