OVH Cloud OVH Cloud

object initialisation

1 réponse
Avatar
AKIRA
Hi,

I am not sure of this, so I need a confirmation.

If I declare an object in a class

like that :
Class toto{

public OtherClass m_otherClass=null;

// Constructeur
toto(OtherClass titi);
{
m_otherClass = titi;
}


void Display()
{
System.out.println("object =" + m_otherClass.name);
for (int i=0; m_otherClass.phoneList.Length(); i++)
{
System.out.println("object =" + m_otherClass.name);
}
}


Java send param by ref, so in Display, what append if object on which we
point via m_otherClass is set to null or overwrite in an other class(remove
or modification of object titi) ?

1 réponse

Avatar
Rémi Cocula
AKIRA wrote:

Java send param by ref, so in Display, what append if object on which we
point via m_otherClass is set to null or overwrite in an other
class(remove or modification of object titi) ?



Si lors de l'appel de ton constructeur toto(OtherClass titi); titi n'est
pas null, et tant que dans ton instance de la classe toto tu ne mets pas
explicitement à null m_otherClass, il n'y a pas de risque.
Un objet n'est détruit que lorsque toutes ses références sont mises à null.
Par contre si une autre instance de classe possède également une référence
sur l'objet pointé par m_otherClass, ce dernier peut bien sûr être modifié
en dehors de la classe toto.


OtherClass other = new OtherClass();
toto unToto = new toto(other);
other.name = "toto li toto";
unToto.Display(); // affiche "toto li toto"
other = null;
unToto.Display(); // affiche toujours "toto li toto"