Voici mon exemple: Je veux savoir s'il est possible de passer un argument initialisé avec null, et d'initialiser ensuite l'objet avec une valeur correcte.Référencement entre classe Objet initialisé avec null
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);
}
}
Maintenant comment j'utilise.
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());
La sortie:
From UserSource:Second Value
From Source:Is not Second
Mais, veulent savoir s'il est possible d'utiliser comme:
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());
Bien sûr, la sortie est
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Est il y a une alternative ?