Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call default interface method which is overridden in superclass [duplicate]

I have a interface and abstract class.

public class TEST extends Abstract implements Inter2{
    void print() {
        toDO();
    }

    public static void main(String[] args) {
        new TEST().toDO();
    }
}

abstract class Abstract {

    public void toDO() {
        System.out.println("Abstract is called");
    }
}

interface Inter2 {

    default void toDO() {
        System.out.println("Inter2 is called");
    }
}

I want to force class interface default methods instead of abstract class.

like image 794
Siva Kumar Avatar asked Sep 11 '15 06:09

Siva Kumar


People also ask

How do you call the overridden method of superclass?

When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

Can default interface methods be overridden?

A class can override a default interface method and call the original method by using super , keeping it nicely in line with calling a super method from an extended class. But there is one catch, you need to put the name of the interface before calling super this is necessary even if only one interface is added.

Can we call default method of interface?

Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

Can interface default methods be overridden in java?

A default method cannot override a method from java.


1 Answers

You'll have to override toDO in the TEST class:

@Override
public void toDO() {
    Inter2.super.toDO();
}
like image 160
JB Nizet Avatar answered Sep 30 '22 03:09

JB Nizet