...

View Full Version : Question about arrays.



Dustfinger
02-22-2008, 01:05 AM
Lets say I create an array of objects.



ObjType[] objArray = new objType[10];
for (int i = 0; i < 10; i++){
objArray[i] = new objType(a,b);
}


Where a and b are integers, and objType has a constructor which adds up a and b and stores the total in an int value called total. How can I, if at all, get the value of total for individual array objects? I tried: objArray[i].total and a number of other things, but none worked. I tried to find something on this on google but I don't really know what it is exactly that I'm searching for. Is there some specific thing I need to do or have I completely misunderstood the way arrays work?

shyam
02-22-2008, 07:02 AM
Where a and b are integers, and objType has a constructor which adds up a and b and stores the total in an int value called total. How can I, if at all, get the value of total for individual array objects? I tried: objArray[i].total and a number of other things, but none worked.

accessing the value of a member variable depneds on the access specifier used like private, public, protected or none (package).

brad211987
02-22-2008, 03:35 PM
The typical way to do this is to provide accessor methods in your objects class. Here is an example object class as you described with accessor methods:



public class MyObject
{
private int total;

public MyObject (int x, int y)
{
total = x + y;
}

public int getTotal()
{
return total;
}
}


Now in your code where you create and call the object:



MyObject obj = new MyObject(5, 6);
int total = obj.getTotal(); //total is assigned the value of 11(5 + 6)


You can use the same method with arrays by using a call such as obj[i].getTotal();

What happens here, is in your objects class, the variable total is a private instance variable, meaning that it can only be directly accessed by methods of that same class. The accessor method getTotal() accesses that variable, and returns its value to the caller of the method. Note that the getTotal() method has a public type, so that it can be called by any other class that creates a reference to the MyObject class.

Dustfinger
02-23-2008, 03:02 AM
Alright, I got it working now. I hadn't thought about whether or not total was even able to be accessed publicly, I just thought I had the wrong syntax or something like that. Thank you brad for the explanation.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum