• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

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).
 
It's weird that we cook bacon and bake cookies. Eat this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic