• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

a question about generics in Chapter 7

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I am doing the self-test question #8 right now for chap 7, and I am confused with option A,
The question is:

Given a method declared as:
A programmer wants to use this method like this:
Will the code compile?
The answer tell me no but why? Why can't I return an arrayList? I tried it and looks like it worked OK. I should be able to return a concrete class obj and a subclass object if the return type specified is an interface type or super class type, can't I?
 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Men Gumani wrote:Hi, I am doing the self-test question #8 right now for chap 7, and I am confused with option A,
The question is:

Given a method declared as:
A programmer wants to use this method like this:
Will the code compile?
The answer tell me no but why? Why can't I return an arrayList? I tried it and looks like it worked OK. I should be able to return a concrete class obj and a subclass object if the return type specified is an interface type or super class type, can't I?


The reason that doesn't work is because the method would return a List<Integer>, and you can't assign a List<Integer> to an ArrayList<Integer> (you need to use explicit casting with downcasting operations.) In other words, List doesn't pass the Is-A test for ArrayList. It is the other way around.
 
Men Gumani
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks buddy!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic