2

If base class and derived class have same field name, then we use super keyword to access base class field. But in case of multilevel inheritance and there also in every class has same field name, how to access field name of super class in child class.

class GrandParent {
  String name;
}

class Parent extends GrandParent {
  String name;
}

class Child extends Parent {
  String name;
  //now here, how to access GrandParent name field
}
kaushik_pm
  • 295
  • 3
  • 10

1 Answers1

2

There is no multiple inheritance here. Your snippet demonstrates field hiding.

Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super.

super allows you to see members only on one level down (=members of the direct parent). Chains like super.super are considered syntactically invalid.

But there are at least two ways to achieve what you want:

  1. (GrandParent)this).name - upcasting to GrandParent
  2. GrandParent.class.getDeclaredField("name").get(this) - extraction by reflection
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142