-
March 5th, 2010, 02:02 PM
#1
change class object
Suppose i have the following classes:
Code:
class testA
{
public int myVar = 12;
}
class testB
{
public testA m_testa;
public testB ( testA testa )
{
this.m_testa = testa
}
}
And my main class
Code:
class Main
{
public void blaat()
{
testA testa = new testA();
testB testb = new testB(testa);
testa.myVar = 400;
}
}
So as you can see i create an instance of classA in my Main class and pass that to classB.
What happends when i directly change a value of classA from my Main class and after that display that same value from classB..??
Will the instance of classA that is in classB also know about that change or will that one still hold the old value??
If that's the case, how can i make it so that when i change a value of classA from Main that the instance of classA in classB will be exactly the same??
-
March 5th, 2010, 04:47 PM
#2
Re: change class object
Good day
Code:
testA testa = new testA();
testB testb = new testB(testa);
testa.myVar = 400;
// here testa.myVar == testb. m_testa.myVar
// if you want to change testa
testa = new testA()
// you have this: testb.m_testa != testa because tesb has the old reference of testa until you change it manually
testb. m_testa = testa;
// and the old reference testb. m_testa will be garbage collected :)
I hope this is what you were asking for.
Thanks
-
March 6th, 2010, 07:41 AM
#3
Re: change class object
Originally Posted by vivendi
Will the instance of classA that is in classB also know about that change or will that one still hold the old value??
Just use the debugger and see for yourself.
-
March 7th, 2010, 02:15 AM
#4
Re: change class object
Originally Posted by vivendi
What happends when i directly change a value of classA from my Main class and after that display that same value from classB..??
If you mean changing the value of classA changing a value of one of its properties, then yes, the new value will reflect in classB instance. That because classA is a reference type. So both references to classA instance in main and classB are pointing to the same object.
If you mean changing the object itself (testa = new testA();) this will make testa in main points to a new object other than the one in B.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|