Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie - Class / Array question

Status
Not open for further replies.

apothis

Programmer
Dec 17, 2001
2
GB
Hi. I'm new to Java, so this may seem to be a really dumb question, caused by my having a total misconception of something, if so, then I apologise. I need what in other languages would be a user defined type, in this case, an object with 5 string vars as members, so I've defined that as a class.

class myClasss{public String a;public String b;public String c; etc etc}

I now need an array of 10 of these, which I declare as myClass[] myClassArray as new myClass[10]; And I want to access the elements and members with myClassArray[0].a = "blah" (meaning the 1st element in the array, and the member 'a') but I'm getting a null pointer reference error.

Can anyone point out to me just what I've misunderstood please? Cheers for any help..;)

Kevin
 
Declaring an array of a type does not create the actual instances in the array's "slots". You have to create the instances by yourself:

Class MyClass {
...
}

...

myClass[] = new myClass[3]; // Create the _array_ instance.

myClass[0] = new myClass(); // Create the MyClass instance.
myClass[0].a = "foo";
...
myClass[1] = new myClass();
myClass[1].b = "bar";
...

 
Ahh, d'oh, excuse me while I beat myself up a bit, that makes sense, thankyou very much!

Cheers

Kevin
 
Hi,
First of all there is no such thing as a dumb question when we are learning.
Ok coming to ur query here goes.
U have declared a new class MyClass, that is right.
U have made an array of 10 of these, that is also right. but u must understand that when u are making the array , u are instantiating that array not the actual elements in the array.In order to access the members of the array u need to instantiate them as well.so ur code must look something like this.

Code:
class MyClass
{
  String a,b,c,d,e;
}

public class Test
{
   // here u are making the array not instantiating  
   //the array members
   MyClass[] arr = new MyClass[10]; 

   //now u instantiate the members of the array
   arr[0] = new MyClass();
   // u have now made the first object
   arr[0].a = "Hello ";
   arr[0].b = "World "; 
   
   // now u can access the member variables of ur class
   System.out.println(arr[0].a+arr[0].b);
}

Happy Learning,
Reddy316
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top