views:

49

answers:

1
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.

+3  A: 

This happens because you can only override methods, not fields. In DerivedClass your hiding the variable filed declared in the BaseClass. An instance of DerivedClass really has 2 fields called filed and you can access both with the appropriate cast. It wouldn't make much sense being able to override fields... Only behavior.

bruno conde