How to call a method in parent class inside of Lambda function in Java?

Viewed 674

I was trying to write the following piece of code, but the error happened on line return super.getAge("Jack"); It showed "The method getAge() is undefined for the type Object". I guess the "super" keyword is not identified here. Does anyone have any suggestions that how to fix this error? Thanks so much!

public class Parent {
    public int getAge(String name) {
       System.out.println("Get the age of the parent.");
       return 40;
    }
}

public class Child extends Parent {

    @Override
    public int getAge(String name) {
        Future<Integer> ageFuture = null;

        @Qualifier("XXX")
        private ExecutorService executorService;

        try {
            ageFuture = executorService.submit(new Callable<Integer>() {
                public int call() throws Exception {
                    return super.getAge("Jack");
                }
            });
        } catch (Exception e) {
            logger.error(" ", e);
        }
        return 10;
    }
}
3 Answers

Try Parent.super.getAge("jack"), though I don't think that will work.

If not, then your only option is to make a bridge method:

public class Child extends Parent {
    private int superGetAge(String name) {
        return super.getAge(name);
    }

    @Override
    public int getAge(String name) {
        .... return superGetAge("jack");
    }
}

Because you are using new Callable() which is instantiating a new class then super.getAge("jack") is referring to a non-existant method.

Instead switch to lambda definition which can reference super.getAge("Jack") directly:

Callable<Integer> call = () -> super.getAge("Jack");
try {
    ageFuture = executorService.submit(call);
}
// etc...

or shorter:

ageFuture = executorService.submit(() -> super.getAge("Jack"));

Youre defining a new class on-the-fly with "new Callable {...} "

That class is inherited from Object.

You could try defining the Parent getAge() as a static method and call it with

Parent.getAge("Jack");
Related