class BaseClass {
protected int filed = 1;
public void method() {
System.out.println("+ BaseClass method");
}
}
class DerivedClass extends BaseClass {
private int filed = 2;
public void method() {
System.out.println("+ DerivedClass method");
}
public void accessFiled() {
System.out.println("DerivedClass: default filed = " + filed); // output 1
System.out.println("DerivedClass: upcasting filed = " + ((BaseClass)this).filed); // output 2
}
public void accessMethod() {
System.out.println("DerivedClass: default method");
method(); // output "+ DerivedClass method"
System.out.println("DerivedClass: upcasting method");
((BaseClass)this).method(); // expecting "+ BaseClass method" but "+ DerivedClass method"
}
}
Why the access to filed(data member) and method differs?Could you explain it to me on both language design and implementation details aspects?
thanks.
This happens because you can only
overridemethods, not fields. InDerivedClassyour hiding the variablefileddeclared in theBaseClass. An instance ofDerivedClassreally has 2 fields calledfiledand you can access both with the appropriate cast. It wouldn’t make much sense being able to override fields… Only behavior.