wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static variables and inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static variables and inheritance" Watch "Static variables and inheritance" New topic

Static variables and inheritance

Ektaa Gargg

Joined: Mar 08, 2008
Posts: 9
Please explain me the output:

class Tree {
private static String tree = "tree ";
string getTree() {return tree; }

class Elm extends Tree {
private static String tree = "elm ";
public static void main(String [] args) {
new Elm().go(new Tree());

void go(Tree t) {
String s = new Elm().getTree();

I want to know that since getTree() is inherited by class Elm then why it does not use its own tree variable.

Ekta Garg<br />(Never say Die,Life is too short to be disheartened.)
Gilles Marceau
Ranch Hand

Joined: Feb 17, 2007
Posts: 78

the thing to see here is that at the line :
String s = new Elm().getTree();
this is the Tree getTree() method that is called (since the Elm class
has no getTree() method). In that case, it means you are using the Tree
part of the Elm object created on the line above. This Tree part doesn't
know its enclosing part, the Elm part with another static variable named
"tree". The Tree part works on its own. So, when the Tree.getTree() method
is invoked, it accesses the Tree.tree static variable, and the program
outputs "tree".

hope it helps

SCJP 1.5<br />SCJD 1.6<br />SCBCD in progress...
Ektaa Gargg

Joined: Mar 08, 2008
Posts: 9
I agree. Here's the link: http://aspose.com/file-tools
subject: Static variables and inheritance
It's not a secret anymore!