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?
change this line
System.out.println(super.i); // 20
to
System.out.println(((A)this).i);
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.