Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to call super method from inner in-place class

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?

like image 265
Vlad Avatar asked Aug 16 '11 14:08

Vlad


3 Answers

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.

like image 69
Kal Avatar answered Oct 03 '22 20:10

Kal


Try this: Bar.super.spam();

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

like image 21
AlexR Avatar answered Oct 03 '22 18:10

AlexR


You can create a wrapper function for this, in Bar

public class Bar...

    public void mySuperSpam(){
        super.spam();
    }
like image 29
Sam DeHaan Avatar answered Oct 03 '22 18:10

Sam DeHaan