• 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:

variables cannot be overridden ?

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


This prints "hello" and does not print "world"

But we put the print() method in class B then it prints "world"



Can someone explain this behaviour
 
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vraiables cannot be overriden but they can be hidden by another variable which has the same name and even a different type. The hider and hidden can even differ on whether it uses the static modifier.

in the overridden method the hidden variable is not visible.
What is visible is the hider vriable and that is what gets used in the derived class.
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Correct: variables, like static methods, cannot be overridden. They can only be obscured. The reference to "xyz" is resolved to the instance variable in class A when the class is compiled. That class B declares a variable of the same name is irrelevant.

Compare this with methods; a reference to the "print()" method in class A would only be resolved when the code is executed; if you have an object of class B, it would call "print()" in class B if it has been overridden there.

- Peter
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vijay,

Welcome to Javaranch

We'd like you to read the Javaranch Naming Policy and change your publicly displayed name (change it here) to comply with our unique rule. Note that, in order to comply with our naming convention, you must supply both a first AND last name. The names need not be real, but they must not be obviously fictitious. Thank you.
[ June 03, 2004: Message edited by: Corey McGlone ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic