This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The following program demonstrates the conversion of an array of objects to legal object ref.types:
It is then stated in my text:
"If line 30 were uncommented then a compilation error would be produced. This is because ITTeacher is not a subclass of EnglishTeacher and the original element type is convertible to the target element type following the rules for class conversion."
Could someone elaborate on what they mean by: 'the original element type is convertible to the target element type'
I think this should read, "...the original element type is not convertible to the target element type..."
The original element type is EnglishTeacher, because this is what we actually created with "new."
EnglishTeacher john = new EnglishTeacher;
Now, an EnglishTeacher is also a Teacher (because EnglishTeacher extends Teacher), and a Teacher is also a Person (because Teacher extends Person), so the following are both valid conversions (i.e., implicit upcasts):
Teacher temp1 = john; Person temp2 = john;
However, an EnglishTeacher is not an ITTeacher, so in the following code...
ITTeacher temp3 = john;
...the original element type (EnglishTeacher) is not convertible to the target element type (ITTeacher). [ February 15, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Oct 04, 2004
Thanks for your reply.
I agree with you that it should be ITTeacher temp3 = john; as at present it would give a compilation error. I think they did this on purpose. Not sure as to why though?
Originally posted by Maureen Charlton: Quoting a text: "This is because ITTeacher is not a subclass of EnglishTeacher"
Unless my lunch is affecting my brain, this should read "ITTeacher is not a superclass of EnglishTeacher". If we hadyou still couldn't assign an EnglishTeacher to an ITTeacher. You can only assign from subtype to supertype with an implicit conversion.
Another thing that's important here is that the important piece is the declaration of the original array -- not the instances it holds. Implicit conversions (i.e. not requiring a cast) only apply to declared types at compile time, not run time instance types.
This example doesn't show it since the declared type and runtime type are the same (EnglishTeacher), but it is important. [ February 15, 2005: Message edited by: David Harkness ]