2
class A {
    int i = 10;
}

class B extends A {
    int i = 20;
}

public class C extends B{
    int i = 30;

    public static void main(String[] args) {
        C c = new C();
        c.m1();
    }

    public void m1() {
        System.out.println(i);       // 30
        System.out.println(super.i); // 20
    }
}

I have a class A, which contains a default variable. I created a child class B which extends class A and one more child class C which extends class B.

I want to access class A variable in child class C m1() method. Is there any direct way to access it?

Eldelshell
  • 6,683
  • 7
  • 44
  • 63
  • 1
    ... why do all those variables have the same name? just give them different names. or, if you need the original value, don't change it – Stultuske Nov 03 '17 at 09:31
  • I seems like class A is your mother class so Why you don't extends class A on the class C ? – F0XS Nov 03 '17 at 09:32
  • @FoxCy he does that, through extending B, wich extends A – Stultuske Nov 03 '17 at 09:33
  • 4
    Possible duplicate of [Why is super.super.method(); not allowed in Java?](https://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java) – Oleg Nov 03 '17 at 09:34
  • @Stultuske I know but in this part of exemple, the class C don't use any method of class B, that's why I suggest to directly use an extends of the A class in C. – F0XS Nov 03 '17 at 09:37
  • 2
    @FoxCy I assume this code is a very minimalistic example to illustrate what he tries to do, not the complete code he's (trying to be) working with – Stultuske Nov 03 '17 at 09:38

2 Answers2

6

change this line

System.out.println(super.i); // 20

to

System.out.println(((A)this).i);
Oleg
  • 6,124
  • 2
  • 23
  • 40
Fermat's Little Student
  • 5,549
  • 7
  • 49
  • 70
1

To complicate your life try this:

public void m1() {
    System.out.println(this.i);
    C c = new C();
    Class<? extends Object> cls = c.getClass().getSuperclass().getSuperclass();
    Field[] fields = cls.getDeclaredFields();
    for ( Field field : fields )
    {
        String in = field.getName();
        int iv = field.get((Object)c);
        System.out.println(iv);
    }
}
oginski
  • 354
  • 5
  • 16