• 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

Polymorphism Problem using Covariant types

 
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

self-made part of it from whiz lab mock questions



If i remove the cast at line 8 then i get

incompatible types
found : java.lang.Object
required: java.lang.String
String aas=aa.foo();


the foo defined in B gets called that has a return typr String,then why am i having this incompatible types
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please QuoteYourSources.
 
Mohit G Gupta
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

mohitkumar gupta wrote:

If i remove the cast at line 8 then i get

incompatible types
found : java.lang.Object
required: java.lang.String
String aas=aa.foo();


the foo defined in B gets called that has a return typr String,then why am i having this incompatible types

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
aa's reference type is A, and it's that that matters as far as the compiler is concerned. So the compiler things the return type on line 8 is Object. So it needs casting to String.

Polymorphism happens at runtime, which is why a String is returned and the cast works.
 
reply
    Bookmark Topic Watch Topic
  • New Topic