Possible Duplicate:
The concept of shadowing
I am confused about how the fields of classes are handled in Java during upcasting. For example:
class SuperClass
{
String myString = "String in SuperClass";
public void myMethod()
{
System.out.println("Method in SuperClass");
}
}
class SubClass extends SuperClass
{
String myString = "String in SubClass";
public void myMethod()
{
System.out.println("Method in SubClass");
}
}
class Question
{
public static void main(String[] args)
{
SuperClass test = new SubClass();
// object test is an instance of SubClass
// but I am telling the compiler to treat it as SuperClass
test.myMethod();
System.out.println(test.myString);
}
}
Output:
Method in SubClass
String in SuperClass //Why is "String in SubClass" not used?
When I create an object test
it is an instance of SubClass
class; however, I am telling the compiler to treat it as SuperClass
. Everything is clear to me about methods work: I will only be able to use the methods of the SubClass
, if a given method is defined for SuperClass
.
However, I am lost as to why a field of a SuperClass
is used when I try to access myString
of test
. Since test
is an instance of SubClass
I would expect myString
defined in SubClass
to be used, why is this not happening? What am I missing?
I know that I can access, myString of SubClass
by using this
operator. For example, I could define printMyString
method in SuperClass, and overwrite it with
public void printMyString()
{
System.out.println(this.myString);
}
In the SubClass
, so my question is mostly about how come the field of the SuperClass
is used in test
. Maybe I am missing something obvious?
I tried to search for the answer, and the closest topic I found was Upcasting in Java and two separate object properties, though helpful, it did not answer my question.
Thank You in Advance