22

I have base class Foo with method spam and class Bar which overrides spam. I need to call spam of base class in method of some callback object which is defined in-place:

public class Foo {
    public void spam() {
        // ...
    }
}

public class Bar extends Foo {
    @Override
    public void spam() {
        objectWhichRequireCallback(new Callback {
            @Override
            public void onCallback() {
                super.spam();
            }
        });
    }
}

This code is not working because super is related to Callback, not Bar class. Is it possible to call super method from object defined in-place?

Vlad
  • 1,631
  • 1
  • 16
  • 21

3 Answers3

34
public class Bar extends Foo {
    @Override
    public void spam() {
        objectWhichRequireCallback(new Callback {
            @Override
            public void onCallback() {
                Bar.super.spam();
            }
        });
    }
}

EDIT : Sorry. DIdn't realize the method names are the same.

Kal
  • 24,724
  • 7
  • 65
  • 65
  • 3
    [StackOverflow](http://stackoverflow.com/questions/7079600/java-how-to-call-super-method-from-inner-in-place-class) ;-) – Alistair A. Israel Aug 16 '11 at 14:22
  • 1
    I was sure that I tried this approach before asking question, but Eclipse gave me error. It seems that I was inattentive. Now I retried. It works! Thanks! – Vlad Aug 16 '11 at 14:34
4

Try this: Bar.super.spam();

Bar.this.spam(); is compiled but it will cause infinite recursion because you call the same spam() itself.

AlexR
  • 114,158
  • 16
  • 130
  • 208
3

You can create a wrapper function for this, in Bar

public class Bar...

    public void mySuperSpam(){
        super.spam();
    }
Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48