-1

Using ((Base)this).f(); instead of super.f() in Derived.f() compiles fine but causes StackOverflowError in Runtime. Why?

class Base {
    void f() {
        System.out.println("Base.f()");
    }
}

class Derived extends Base {
    void f() {
        ((Base)this).f(); //instead of super.f();
        System.out.println("Derived.f()");
    }
}

public class MyTest {
    public static void main(String[] args) {
        new Derived().f();;
    }
}
LrnBoy
  • 373
  • 1
  • 2
  • 9
  • What do you think `((Base)this)` does? Why do you think so? – Sotirios Delimanolis Jan 22 '17 at 19:15
  • As per your link, this is definitely not a duplicate! I would appreciate if anybody pointed to a true duplicate thou! – LrnBoy Jan 22 '17 at 19:28
  • I think you're misunderstanding what a duplicate is. The answer there states: _Any method is dispatched (selected/invoked) dynamically according to the actual type of the object in stead of the type by which it is being referred to._ That's the answer to your question here, regardless of the `StackOverflowError`. That's just a side effect. – Sotirios Delimanolis Jan 22 '17 at 19:30
  • 1
    The typecasting of `this` to reference type `Base` has no effect; the object type is still `Derived`, so `Derived.f()` is called, thus `Derived.f()` is calling itself, causing a `StackOverflowError`. `(Supertype) this` is not the same as `super`. See [this answer](http://stackoverflow.com/a/16730147/507738). – MC Emperor Jan 22 '17 at 19:56

1 Answers1

1

Since f() of Derived overrides f() of Base, in runtime f() of Derived (and not f() of Base) is executed even if you are invoking it via a reference to type Base.

Therefore

void f() {
    ((Base)this).f();
    System.out.println("Derived.f()");
}

is equivalent to

void f() {
    f();
    System.out.println("Derived.f()");
}

Your f() method is calling itself, which results in StackOverflowError.

Eran
  • 387,369
  • 54
  • 702
  • 768