• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Question regarding covariant returns

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class First {
public Object method1() {
return new String("Based");
}
}

class Second extends First {
public String method1() {
return new String("Derived");
}
}

public class covariant {
public static void main(String[] args) {
First o = new Second();
String s = (String) o.method1();
System.out.println(s);
}
}

For the above code, why does it print Derived instead of Based?
The reference variable of o is First and method1 should be called in First instead of Second

Thanks
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer really doesn't have anything to do with the return types. When an instance method is called on an object whose runtime type is the subclass, it doesn't matter what the reference type is, the overidden method is called.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Keith said, it's polymorphism at work. It has nothing at all to do with covariant return types.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic