GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generic Subtyping - Method Call with Subtype Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generic Subtyping - Method Call with Subtype" Watch "Generic Subtyping - Method Call with Subtype" New topic
Author

Generic Subtyping - Method Call with Subtype

Salman Riaz
Ranch Hand

Joined: Jul 24, 2003
Posts: 53
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

Joined: Jul 25, 2006
Posts: 129
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.


Ashok<br /> <br />SCJP 91%<br />SCWCD 88%
Salman Riaz
Ranch Hand

Joined: Jul 24, 2003
Posts: 53
Ashok,

Many Thanks DUDE!
that explains...

Salman
 
GeeCON Prague 2014
 
subject: Generic Subtyping - Method Call with Subtype