Home > front end >  Overridng either both default function or no function from java interface
Overridng either both default function or no function from java interface

Time:04-17

I am trying to build a encryption and decryption of string interface and there is class that is overriding that interface. Now, i want to do something that can make, if any class is implementing the interface, either that class override no default function of that interface or all the function of that interface. Is there a way of doing that?

public interface encryptAlgorithm {
    default String encyrption(String str) {
        //some code
        
    }
    default  String decryption(String str) {
        //some code
        
    }
}
public class EncryptAlgorithmImpl implements encryptAlgorithm{
    
    public String encrypt(String str) {
        //some code
        
    }
    
    public  String decrypt(String str) {
        //some code
    }   
}

CodePudding user response:

If you want to achieve that, your default implementations should not be inside the interface, but instead they should be in a separate class, e.g. DefaultEncryptAlgorithm that implements your interface.

Then, if you want to override none of the default implementations, you can use or derive from DefaultEncryptAlgorithm, and if you want to override both methods, you can implement the interface directly.

  • Related