• 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

Casting question

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Base {
public static final String FOO = "foo";
public static void main(String[] args) {
Sub s = new Sub();
System.out.print(((Base)s).FOO);
}}

class Sub extends Base {public static final String FOO="bar";}


Can anybody explain why i am getting "Foo".
I was thinking "bar" since s is referring to Sub.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Polymorphism applies to methods (which can be overridden), but does not to variables (which cannot be overridden, but can instead be hidden).

Try the following code, first with the overridden method, then without the overridden method...
 
Manishi Manush
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Marc for the explanation. I am guessing in my case the variable was hidden.
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would have said that the reason you got foo instead of bar is that you cast the reference variable to be of type (Base). It seems to me that the compiler determines which variable to use based on the reference type. Try changing the object instantiation in Marc's code to read:



Somebody please correct me if I'm wrong (especially the part about the compiler determining which variable to use).
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic