Click to See Complete Forum and Search --> : accessing class fields


kikkoman
03-30-2005, 04:32 PM
say i have

public class test
{
public int a;
}

public class changeValue
{
public changeValue()
{
test[] b = new test[5];
for (int i=0;i<5;i++)
// I want to edit the value of 'a', for each instance of 'b'
}
}

how can this be done?

JGRobinson
03-31-2005, 09:03 AM
Hi,

b[i].a = whatever should do it

i.e.


public class changeValue
{
public changeValue()
{
test[] b = new test[5];
for (int i=0;i<5;i++)
{
// I want to edit the value of 'a', for each instance of 'b'
b[i].a = 1;
}
}
}


It is bad practice however to access "a" directly, should use a setter which could
then be validated providing an interface to the class.

kikkoman
03-31-2005, 10:16 AM
I know that it is bad practice, but it's something i have to do. i assumed that b[i].a=what ever; would work, but for some reason i get a null error. if if i put a method inside the class with a, to change a, i get an error. Both of these work correctly if i dont have b as an array. why is this? a is not static, so each instance of b should have it's own value for a.

JGRobinson
03-31-2005, 01:49 PM
Hi,

I didn't mean to cause any upset, but as you know doubt know, sometimes you need to state the obvious - from your reply however this wasn't one of those times. Please accept my apologies.

Back to the problem in hand.

I think that the line test []b = new test[5] just allocates the array and
not the elements pointed to by the array.

This code looks to work ok


public class changeValue
{
public static void main(String[] args)
{
changeValue cv = new changeValue();

}


public changeValue()
{
test []b = new test[5];
for (int i=0;i<5;i++)
{
// I want to edit the value of 'a', for each instance of 'b'
b[i] = new test();
b[i].a = i;
}

for (int i=0;i<5;i++)
{
// I want to edit the value of 'a', for each instance of 'b'
System.out.println(b[i].a);
}

}
}


Please come back if you have any further difficulties.

kikkoman
04-03-2005, 06:48 PM
Thx, that helped. :D

meisl
04-05-2005, 11:53 AM
Those arrays seem to pose problems - maybe you want to also see here (http://forums.devx.com/showthread.php?t=141990).