Why can't a reference, which is assigned to a child class, access the child class's members
class pract1 {
String s="s1";
public String getS()
{
return s;
}
}
class pract extends pract1{
String a="s2";
public String getS() {
return a;
}
public static void main(String[] args) {
pract1 parent= new pract1();
pract child= new pract();
paren开发者_如何学运维t=child;
System.out.println(parent.a); // syntax error it should be (parent.s);
System.out.println(parent.getS());
}
}
Here i am assigning child
to parent
. Using the parent
reference, I should be able to access the a
field. However, that is giving a compile error. Why?
You can't access a child class's instance variable from a parent class reference because the binding is at compile time (and during compile time it is very clear that 'a' is not part of pract1) unlike the overridden methods which are bound runtime i.e. dynamic binding
I think you need to mark it protected or public to be readable by your descendent.
e.g.
protected String s;
Tried, does not seem to give any error and does exactly as shown in the snippet.
Prints out "s1" and then "s2"
although it is generally good practice to declare the variables visibility.
This has to do with the apparent type of the reference versus the actual type of the reference.
If you do this:
pract1 p = new pract();
then the apparent type is "pract1". And the actual type is "pract"
The apparent type is known at compile time. That is, the compiler does type checking against the apparent type. So when you attempt to access members of the sub class, as far as the compiler is concerned the super class does not have those members so its an error.
This is necessary because a reference to pract1 may not necessarily refer to an instance of pract. The compiler takes no chances.
At run time however, the actual type is used.
精彩评论