I am studying overriding member functions in JAVA and thought about experimenting with overriding member variables.
So, I defined classes
public clas
This is called variable hiding. When you assign aRef = b;
, aRef
has two intVal, 1 is named just intVal
another is hidden under A.intVal
(see debugger screenshot), Because your variable is of type class A
, even when you print just intVal
java intelligently picks up A.intVal
.
Answer 1: One way of accessing child class's intVal
is System.out.println((B)aRef.intVal);
Answer 2: Another way of doing it is Java Reflection because when you use reflection java cant intelligently pickup hidden A.intVal
based on Class type, it has to pick up the variable name given as string -
import java.lang.reflect.Field;
class A{
public int intVal = 1;
public void identifyClass()
{
System.out.println("I am class A");
}
}
class B extends A
{
public int intVal = 2;
public void identifyClass()
{
System.out.println("I am class B");
}
}
public class Main
{
public static void main(String [] args) throws Exception
{
A a = new A();
B b = new B();
A aRef;
aRef = a;
System.out.println(aRef.intVal);
aRef.identifyClass();
aRef = b;
Field xField = aRef.getClass().getField("intVal");
System.out.println(xField.get(aRef));
aRef.identifyClass();
}
}
Output -
1
I am class A
2
I am class B