0
public class Test3 {
    public static void main(String[] args) {
        Derived04 b = new Derived04();
        Base04 a = (Base04)b;
        System.out.println(a.i);
        System.out.println(a.f());
    }
}

class Base04 {
    int i=1;
    public int f() {return i;}
}
class Derived04 extends Base04 {
    int i = 2; 
    public int f(){return -i;}
}

Both classes include the f() method so when I cast d onto a which method does it go to when I call a.f()? I thinking since a is declared as Base04 type when you do a.i it gives 1 but then why does it use the method from the subclass?

Jae
  • 3
  • 1
  • You should (re)read the section about method overriding in your Java learning guide. – Andreas Apr 25 '20 at 05:12
  • After looking at your question, I think that the interesting point isn't why it calls the method from the implemented class, which is what it is expected to do I think, but why it's printing `1` in `System.out.println(a.i)`. I think you should append the execution output to your question and ask about this point. – beni0888 Apr 25 '20 at 06:14

2 Answers2

0

why does it use the method from the subclass?

You create an object of Derived04 class you just cast it to the type Base04. It is still Derived04 implementation.

itpr
  • 404
  • 2
  • 15
0

The whole point is about implementing and casting. so when you create a Derived04 then you have implemented a Derived04 class, not its parents Base04 so even if you cast it like that it will run the implemented method not the casting method unless there is a different between f() in both classes. and that's not our case.

Amir Hossein
  • 319
  • 2
  • 14
  • What do you mean by difference between `f()`? As in if `Derived04` had `f(int x)` and `Base04` has `f()`? ie difference in parameter or such? – Jae Apr 25 '20 at 20:27
  • for example if you change one of those ```f()``` to ```f(int x)``` then those two come apart and will be used in different conditions. – Amir Hossein Apr 25 '20 at 20:40