Working with Arrays of Objects with Java and NetBeans IDE - How to Create Arrays of Objects in Java: Explanation
(Page 5 of 6 )
There is nothing special in the class “MyCalc.” We need to focus only on the testing code. Let us go through the code step by step.
MyCalc[] ar = new MyCalc[10];
The above statement will simply create ten locations to store objects of type “MyCalc.” The important issue is that it creates only the location, but not the objects. Each of those locations can hold an object of type “MyCalc.” Proceeding further, we have the following:
for(int i=0;i<10;i++) {
The above loop simply iterates from zero through nine. Next, we have the following statement:
ar[i] = new MyCalc();
The above statement creates a new instance/object of the class “MyCalc” and stores that instance at the ‘i’th location in array “ar.” Proceeding further, we have the following:
ar[i].setValues(i*10,i*10+1);
Once the object is successfully created (at some location in the array), we need to set some values to its members. The same is achieved through the above statement.
Now it is time to display the sum of all values (in all objects) available in the array. Again, we need to iterate through all the objects in the array and sum up those values. The same is achieved through the following:
int s=0;
for(int i=0;i<10;i++) {
s += ar[i].getSum();
}
We finally display the sum using the following:
this.lblMsg.setText("Sum = " + String.valueOf(s));
Next: Passing Arrays of Objects to Methods in Java: Demo >>
More Java Articles
More By Jagadish Chaterjee