Stack Holder Stack Holder - 4 months ago 12
Java Question

How can i get the value of a variable through the Super keyword?

I have three class

A
,
B
,
C
class B extends A and class C extends B.

I want to get the value of the integer
a
present in the
class A
and print that value in
class C
. My first choice is to print through
super
keyword.

package testee;
import java.util.Scanner;


public class Testee {

public static void main(String[] args) {

new C();

}
}


class A{

int a=10;

A(){

System.out.println(a);
}

}


class B extends A{

int a=13;

B(){

System.out.println(a);
}

}


class C extends B{

int a=21;

C(){

System.out.println(super.a);
}
}

k5_ k5_
Answer
System.out.println(((A)this).a);

Having fields with the same name multiple times in a inheritance hierarchie is called "hidden fields".

Access to fields (and static methods) is based on the (static) type of the reference used. So that means if you cast the reference(here this) the type you want (in that case A) and access the field you get the field that belongs to A.

Would work the same way if you assign C to a variable. If the variable is of type A, you will get A.a.

Anyway: please, do not use hidden fields in production code