2

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;
    }
}
Gaoyang
  • 41
  • 1
  • 5

3 Answers3

2

Because you are using new Callable() that will instantiate an anonymous class as child of Callable, not Parent, so 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"));
DuncG
  • 12,137
  • 2
  • 21
  • 33
1

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");
    }
}
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Thanks so much, the second way is quite a simple but a smart way! "Parent.super.getAge("jack")" does NOT work. – Gaoyang Nov 10 '20 at 23:35
-1

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");