• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Subtyping - Method Call with Subtype

 
Salman Riaz
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Respected Gurus!

I am new to generics and cannot figure out the difference in the two implementations shown in the methods below:

GenericMethodSubtyping.someMethod1(l1);
System.out.println(l.get(counter));// why i cannot call getSValue() method?


GenericMethodSubtyping.someMethod(l2);
System.out.println(l.get(counter).getSValue()); // Why i can call getSValue() here

i know
l2 = l1; //compile time error
l3 = l1; // compile time error
=======================================================

=====================================================
OUTPUT:
A1
A2
A3
B1
B2
B3

*****************************************************

please explain!

thanks
salman

[BPSouther: Added code tags]
[ April 03, 2008: Message edited by: Ben Souther ]
 
Ashok Kumar Babu
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Salman,

1.
GenericMethodSubtyping.someMethod1(l1);
System.out.println(l.get(counter));// why i cannot call getSValue() method?


Let us check this condition first.



In the above declaration <A> does not represent Class A, so only the method getSValue is not available. <A> is just to indicate the generics - any instance, again the <A> before the void gives the explanation about it. To understand it clearly, the above statement is very similiar to the below.



So whats the way to say only Instance A.



See the missing before the void. this above declaration clearly says only instance of class A. With this declaration you can get getSValue() method.

2.


This is similar to Somemethod1 but while describing the generics it clearly says any class which is a sub class of Class A. So obviously objects in the list can be cast to Class B automatically, hence the getSValue method is available.


If anything is wrong in my explanation. please mark it out.
 
Salman Riaz
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashok,

Many Thanks DUDE!
that explains...

Salman
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic