0

Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.

private class Source {
  String str;
  String getStringValue() {
    return str;
  }
  void setStringValue(String str) {
    this.str = str;
  }
}

private class UserSource {
  Source src;
  UserSource(Source src) {
    this.src = src;
  }
  String getValue() {
    return src.getStringValue();
  }
  void setValue(String str) {
    src.setStringValue(str);
  }
}

Now how I'm using.

  Source srcW = new Source();
  UserSource userSourceW = new UserSource(srcW);
  srcW.setStringValue("Second Value");
  System.out.println("From UserSource:" + userSourceW.getValue());
  userSourceW.setValue("Is not Second");
  System.out.println("From Source:" + srcW.getStringValue());

The output:

From UserSource:Second Value
From Source:Is not Second

But, want to know if is possible to use like:

  Source srcN = null;  // YES I want to assign Not initialized!
  UserSource userSourceN = new UserSource(srcN);
  srcN = new Source();
  srcN.setStringValue("First Value");
  System.out.println("From UserSource:" + userSourceN.getValue());

Of course the output is

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Is there an alternative?

Cecilya
  • 519
  • 1
  • 5
  • 20

1 Answers1

0

Unfortunately, it's not possible to do so. When the value is initially null, then you're passing the null reference. Later you initialize it with srcN = new Source();, but then you're rewriting the source.

You could work around it with a Reference<Source>. But that would only make the code more cumbersome. Moreover, the Source class is a perfect candidate to pass it as an empty source, and then initialize it later with setString().

Am I missing something? What's your problem with the code as is?

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49