0

I have parent class :

class Parent {

  public void some() {
     return 10;
  }

    public String LAST_UPDATED_KEY = "parent_updated";
        public String getLastUpdated(String key) {
         // do some stuff
         System.out.println(key);  // prints parent_updated
         System.out.println(this.some())  // prints 5

        }

        public String getLastUpdated() {
            return this.getLastUpdated(this.LAST_UPDATED_KEY);
        }
    }

here is child class :

class Child extends Parent {
public String LAST_UPDATED_KEY = "child_updated";
  // some stuff
  public void some() {
     return 5;
  }
}

I am calling it using reflection as :

public void somemethod() {
        Class<? extends Parent> daoClass = (Class<? extends Parent>)Class.forName(Child.class);
        Method getInstance = daoClass.getMethod("getInstance");
 Parent child = getInstance.invoke(null);
 child.getLastUpdated(child.LAST_UPDATED_KEY) 

}

i did't understand why it prints parent's last updated key not child's and it do call some() method on child . Please explain behaviour. Thanks

  • The keyword is ["shadowing"](http://www.dummies.com/programming/java/shadowed-classes-or-variables-in-java/), i.e. `Parent` sees its own `LAST_UPDATED_KEY` while `Child` shadows/hides it and thus any code in `Child` or further subclasses sees the version in `Child` while code in `Parent` sees and uses the version in `Parent`. Replace the new declaration in `Child` with an instance initializer block instead: `class child{ ...{LAST_UPDATED_KEY = "child_updated"} ... }`. – Thomas Jan 13 '17 at 14:40
  • 2
    Fields are not polymorphic. Only instance methods are. You can not override a field, only a method. – JB Nizet Jan 13 '17 at 14:42
  • is there any other solution, apart from static initializer ? – Amit Kumar Kannaujiya Jan 13 '17 at 14:53
  • Static initializers are irrelevant. If you want polymorphism, use methods. It's as simple as that. Or pass the constant field value as parameter of the super constructor. – JB Nizet Jan 13 '17 at 15:08

0 Answers0