Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: problem with array of class objects
|
Posted: Mar 21, 2003 7:09 PM
|
|
You've got a couple problems. First, when you create an array, think of it as creating an array of empty slots. You still need to create an object to stick in each slot. Additionally, to access the items in the array, you need to specify which item you want to access, which you do with the index, inside the square brackets. Finally, a typo probably, but you declared MasterPID and TestPID, then tried to access MasterID and TestID.
Here's your example with the necessary tweaks to get it compiling and running (I assume the Data class and the TestArray class are in separate files):
public class Data
{
String MasterPID;
String TestPID;
}
public class TestArray extends Data
{
public static void main(String[] args)
{
Data[] test = new Data[2];
for(int i=0; i < test.length; i++)
{
test[i] = new Data();
test[i].MasterPID = "One";
test[i].TestPID = "Two";
}
for( int i=0; i < test.length; i++ )
System.out.println( (i+1) + ". " +
test[i].MasterPID + " - " +
test[i].TestPID );
}
}
By the way these are objects, but they aren't class objects.
Finally, this shows you how to use an array in Java, but from a stylistic point of view, it is very bad code. A derived class usually should avoid mucking with the members of its super class and it is especially bad to have some static method doing it, as in this case. For this case, you would probably have a constructor in the Data class (which, by the way, could have a much more descriptive name) which intializes its own members with parameters passed to it. Also, it doesn't look like there is any good reason for TestArray to be extending Data; in fact there is only one reason and it is a bad one: so it can access its member data.
So, here is an improved version:
public class TestData
{
private String masterPid;
private String testPid;
public TestData( String masterPID, String testPID )
{
masterPid = masterPID;
testPid = testPID;
}
public String toString()
{
return masterPid + " - " + testPid;
}
public String getMasterPid()
{
return masterPid;
}
public String getTestPid()
{
return testPid;
}
}
public class TestArray
{
public static void main(String[] args)
{
TestData[] test = new TestData[10];
for(int i=0; i < test.length; i++)
test[i] = new TestData( "Master ID " + i, "Test ID " + i );
for( int i=0; i < test.length; i++ )
System.out.println( (i+1) + ". " + test[i] );
}
}
|
|