0

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?

Eran
  • 387,369
  • 54
  • 702
  • 768
Thanos Paravantis
  • 7,393
  • 3
  • 17
  • 24

3 Answers3

2

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");
Eran
  • 387,369
  • 54
  • 702
  • 768
0
public class Example{
   private Object object1;
   public Example(){ 

   }

   public void setObject1(Object o){
      this.object1 = o;
   }
}

Now you can use this as follows:

Example example = new Example();
example.setObject1(someObject);
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69
0

As noted by others and yourself already, there is no easy / official way of object construction when you can't provide the parameters needed.

You may want to look at the Objenesis project. They provide clever ways of instantiation of objects in non-standard ways. To my knowledge sometimes being able to instantiate objects without providing the usually mandatory arguments declared by the constructors.

Hille
  • 4,096
  • 2
  • 22
  • 32