File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables and inheritance

 
Ektaa Gargg
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gilles Marceau
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ektaa Gargg
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic