• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static variables and inheritance

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
 
Why is the word "abbreviation" so long? And this ad is so short?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic