Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Interface.super

Tags:

java

I have recently used default methods in java. In its implementation I found

public interface DefaultMethod {
    default String showMyName(String name){
        return "Hai "+name;

    }
}


public class DefaultMethodMainImpl implements DefaultMethod{

    @Override
    public String showMyName(String name){
        return DefaultMethod.super.showMyName(name);

    }
}

My question is in DefaultMethod.super where super will call it have no super class except Object? what super will return?

like image 336
Robin Avatar asked Aug 31 '16 11:08

Robin


People also ask

What is interface super class?

Interfaces are not classes. Therefore, an interface cannot have a superclass, and your question is essentially invalid. Is Interface a class?

Do you use super with interface?

The super keyword can be used as a qualifier to invoke the overridden method in a class or an interface.

What does super () do in Java?

The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.

Can we use super super in Java?

Your code would break if you called a super of a super that had no super. Object oriented programming (which Java is) is all about objects, not functions. If you want task oriented programming, choose C++ or something else.


2 Answers

If you use super in a class it usually refers to the ancestor of that class (either the extended class or Object).

In the case of overriden default method of an interface you have to specify the specific interface which default implementation you want to invoke, hence

<Interface>.super.<method>();

See also The diamond problem.

like image 68
Markus Mitterauer Avatar answered Nov 13 '22 15:11

Markus Mitterauer


<Interface>.<method>(); would consider <method> as static, and this is not the case. Hence the use of key word super which is a reference variable that is used to refer a "parent" object.

like image 43
Najib Tounsi Avatar answered Nov 13 '22 17:11

Najib Tounsi