Search code examples
javainstances

Can an instance complete its arguments later?


I wonder if there is any way that I can declare a new instance with parameters, do not fill them, and just set them later.

Here is an example:

private Example example = new Example() // Need 1 parameter.

public void foo(Object arg1)
{
   example = new Example(arg1);
}

It is clear that this is not possible, but is there a way to do something similar to that?


Solution

  • You can always use a parameter-less constructor, and then set the properties of the created instance later.

    ....
    public Example ()
    {
        this.s = null;
    }
    
    public Example (String s)
    {
        this.s = s;
    }
    ....
    public void setS (String s)
    {
        this.s = s;
    }
    ....
    Example ex = new Example ("something");
    Example ex2 = new Example ();
    ex2.setS("Something Else");