Accessing Same Name Data Members In Main Method Using obj Object not creating object in Class A and Class B.
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
class C extends B {
int i = 30;
}
public class Main {
public static void main (String[] args) {
C obj = new C ();
System.out.println (obj.i);
//How to access Class A variable
//How to access Class B Variable
}
}
Print Class A Variable Print Class B Variable Without Creating Object of Class A and Class B.
System.out.println (((A) obj).i);
and System.out.println (((B) obj).i);
respectively. If they were protected
fields, they would be inherited. As is, they are hidden ( shadowed ) package-private fields.
Since you've now mentioned that you cannot use a simple cast, the next best option (I can think of) is reflection . You can iterate the Field
(s), find the field named i
, make it accessible and then print it (and the class name). For example,
try {
Class<?>[] classes = { A.class, B.class, C.class };
for (Class<?> cls : classes) {
for (Field f : cls.getDeclaredFields()) {
if (f.getName().equals("i")) {
f.setAccessible(true);
System.out.printf("%s %s%n", cls.getSimpleName(), f.get(obj));
}
}
}
} catch (IllegalArgumentException | IllegalAccessException | SecurityException e) {
e.printStackTrace();
}
Outputs
A 10
B 20
C 30
Use the Reflection. You can get the super class and get the i value. This approach don't use the typeCasting, create object and statie member. I think it will help you.
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
class C extends B {
int i = 30;
}
public class Main {
public static void main (String[] args) {
try {
C obj = new C();
System.out.println(obj.i);
// get the Class B
Class b = obj.getClass().getSuperclass();
System.out.println(b.getDeclaredField("i").getInt(obj));
// get the Class A
Class a = b.getSuperclass();
System.out.println(a.getDeclaredField("i").getInt(obj));
} catch (Exception e) {
// ignore
}
// Output
// 30
// 20
// 10
}
}
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.