Variable shadowing in Java -


this question has answer here:

i having doubts java code. output gives "furry bray". questions:

  1. why output?
  2. how can access string object reference "name" in zookeeper class?
  3. if has variable shadowing, variable being shadowed?

code:

class mammal {    string name = "furry ";    string makenoise() { return "generic noise"; }  }  class zebra extends mammal {    string name = "stripes ";    string makenoise() { return "bray"; }  }  public class zookeeper {    public static void main(string[] args) { new zookeeper().go(); }    void go() {      mammal m = new zebra();      system.out.println(m.name + m.makenoise());      //output comes "furry bray". please explain this.      //and how can access name variable, 1 having "stripes " in it.      //does have variable shadowing?    }  } 

variables aren't polymorphic. when access m.name, always use mammal.name field part of object, regardless of execution-time type of object. if need access zebra.name, need expression compile-time type of zebra.

the makenoise method called virtually though - implementation used @ execution time does depend on type of object.

note if make fields private - idea anyway - doesn't end being issue.

this hiding rather shadowing. see jls section 8.3 details on hiding, , section 6.4.1 shadowing. can't keep differences straight...


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -