How would I overload method in an interface?

前端 未结 4 846
一个人的身影
一个人的身影 2021-02-09 00:30

if I have this interface

public interface someInterface {
  // method 1
  public String getValue(String arg1);
  // method 2
  public String getValue(String arg1         


        
4条回答
  •  孤独总比滥情好
    2021-02-09 00:53

    As of Java 8, you can have an interface provide an implementation of a method, through the use of the default keyword. Therefore a new solution would be to provide a default implementation of both methods which maybe throws an exception, then derive the actual implementation from the default interface.

    Anyways here is how you can do this:

    public interface SomeInterface {
        // method 1
        default String getValue(String arg1) {
            // you decide what happens with this default implementation
        }
    
        // method 2
        default String getValue(String arg1, String arg2) {
            // you decide what happens with this default implementation
        }
    }
    

    Finally, make the classes override the correct methods

    public class SomeClass1 implements SomeInterface {
        @Override
        public String getValue(String arg1) {
            return arg1;
        }
    }
    
    public class SomeClass2 implements SomeInterface {
        @Override
        public String getValue(String arg1, String arg2) {
            return arg1 + " " + arg2;
        }
    }
    

提交回复
热议问题