aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static variables and inheritance" Watch "Static variables and inheritance" New topic
Author

Static variables and inheritance

Ektaa Gargg
Greenhorn

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();
System.out.println(s);
}
}

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
Hi,

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
Greenhorn

Joined: Mar 08, 2008
Posts: 9
Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static variables and inheritance
 
Similar Threads
Creating JTree On Run TIme
Help with Jtree
Doubt about sub-super class relationship
need help with jTree isNodeAncestor()
JTree last selected path component is giving null