1
class A { public int a = 100; } // End of class A
class B extends A { public int a = 80; } // End of class B
class C extends B { public int a = 60; } // End of class C
class D extends C { public int a = 40; } // End of class D

class E extends D{
    public int a =10;

    public void show(){
        int a =0; 
        // Write Java statements to display the values of
        // all a’s used in this file on System.out
    } // End of show() Method
}// End of class E

I am trying to access the variable a of the superclasses A,B,C from E but I don't understand how to do it. I tried something like this

System.out.println(super.a+" "+super.super.a+" "+super.super.super.a+" "+
                   super.super.super.super.a);
Leon
  • 2,926
  • 1
  • 25
  • 34

1 Answers1

2

Since A, B, C, D are superclass of E, we can cast E to supertype and access the field.

System.out.println(((A) this).a); //Prints 100
System.out.println(((B) this).a); //Prints 80
System.out.println(((C) this).a); //Prints 60
System.out.println(((D) this).a); //Prints 40
Bernard
  • 304
  • 2
  • 11