Does Java support default parameter values?

后端 未结 25 1590
清歌不尽
清歌不尽 2020-11-22 07:07

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}         


        
25条回答
  •  清酒与你
    2020-11-22 07:30

    A similar approach to https://stackoverflow.com/a/13864910/2323964 that works in Java 8 is to use an interface with default getters. This will be more whitespace verbose, but is mockable, and it's great for when you have a bunch of instances where you actually want to draw attention to the parameters.

    public class Foo() {
        public interface Parameters {
            String getRequired();
            default int getOptionalInt(){ return 23; }
            default String getOptionalString(){ return "Skidoo"; }
        }
    
        public Foo(Parameters parameters){
            //...
        }
    
        public static void baz() {
            final Foo foo = new Foo(new Person() {
                @Override public String getRequired(){ return "blahblahblah"; }
                @Override public int getOptionalInt(){ return 43; }
            });
        }
    }
    

提交回复
热议问题