3

The Calculator interface has calculate abstract method and ramdom() non-abstract method. I want to use super ramdom() and also Override ramdom() at concrete class CalculatorImpl. My question is why I have to call like that Calculator.super.ramdom() ? Why super.ramdon() don't work?

public interface Calculator {

    double calculate(int a);

    default double ramdom() {
        System.out.println("Calculator ramdom");
        return Math.random();
    }

}

class CalculatorImpl implements Calculator {

    @Override
    public double calculate(int a) {
        // calling super.ramdom() will get [The method ramdom() is undefined for
        // the type Object error]
        return Calculator.super.ramdom() * a;
    }

    @Override
    public double ramdom() {
        System.out.println("CalculatorImpl ramdom");
        return 0;
    }

}
Mizuki
  • 2,153
  • 1
  • 17
  • 29

2 Answers2

2

To answer your exact question: when you use super inside a class ... you are "pointing" to the class it is extending; in this case Object.

But Object does not have a method random that you could be calling.

Therefore you have to make it explicit "where" random is actually coming from.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Just remove the override of ramdom in CalculatorImpl. It will implicitly used the default implementation from Calculator.

class CalculatorImpl implements Calculator {

@Override
public double calculate(int a) {
    // calling super.ramdom() will get [The method ramdom() is undefined for
    // the type Object error]
    return Calculator.super.ramdom() * a;
}
/* Remove the Override and the default implementation will be used
@Override
public double ramdom() {
    System.out.println("CalculatorImpl ramdom");
    return 0;
}
*/
}

Keyword super is used to call the inherited class and not the implemented interface. But here you have no inheritance except the implicit Object which does not have a random method

Edit: I might have missunderstood your question. If you want to override and call the default implementation, check the link provided by Sasha Salauyou

Community
  • 1
  • 1
ortis
  • 2,203
  • 2
  • 15
  • 18