Does Java support default parameter values?

后端 未结 25 1588
清歌不尽
清歌不尽 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:27

    I might be stating the obvious here but why not simply implement the "default" parameter yourself?

    public class Foo() {
            public void func(String s){
                    func(s, true);
            }
            public void func(String s, boolean b){
                    //your code here
            }
    }
    

    for the default, you would either use

    func("my string");
    

    and if you wouldn't like to use the default, you would use

    func("my string", false);
    
    0 讨论(0)
  • 2020-11-22 07:28

    No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).

    For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.

    0 讨论(0)
  • 2020-11-22 07:28

    You can do this is in Scala, which runs on the JVM and is compatible with Java programs. http://www.scala-lang.org/

    i.e.

    class Foo(var prime: Boolean = false, val rib: String)  {}
    
    0 讨论(0)
  • 2020-11-22 07:28

    This is how I did it ... it's not as convenient perhaps as having an 'optional argument' against your defined parameter, but it gets the job done:

    public void postUserMessage(String s,boolean wipeClean)
    {
        if(wipeClean)
        {
            userInformation.setText(s + "\n");
        }
        else
        {
            postUserMessage(s);
        }
    }
    
    public void postUserMessage(String s)
    {
        userInformation.appendText(s + "\n");
    }
    

    Notice I can invoke the same method name with either just a string or I can invoke it with a string and a boolean value. In this case, setting wipeClean to true will replace all of the text in my TextArea with the provided string. Setting wipeClean to false or leaving it out all together simply appends the provided text to the TextArea.

    Also notice I am not repeating code in the two methods, I am merely adding the functionality of being able to reset the TextArea by creating a new method with the same name only with the added boolean.

    I actually think this is a little cleaner than if Java provided an 'optional argument' for our parameters since we would need to then code for default values etc. In this example, I don't need to worry about any of that. Yes, I have added yet another method to my class, but it's easier to read in the long run in my humble opinion.

    0 讨论(0)
  • 2020-11-22 07:29

    No, but you can use the Builder Pattern, as described in this Stack Overflow answer.

    As described in the linked answer, the Builder Pattern lets you write code like

    Student s1 = new StudentBuilder().name("Eli").buildStudent();
    Student s2 = new StudentBuilder()
                     .name("Spicoli")
                     .age(16)
                     .motto("Aloha, Mr Hand")
                     .buildStudent();
    

    in which some fields can have default values or otherwise be optional.

    0 讨论(0)
  • 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; }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题