2 Replies - 675 Views - Last Post: 16 February 2011 - 05:25 AM Rate Topic: -----

#1 LaVeritas   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 10-February 11

accessing methods of objects held in a array

Posted 16 February 2011 - 03:39 AM

Hi folks,

this is propably a pretty dumb question but still, I need help here.

Let's say I have 20 "Dog" objects(dog_0, dog_1, dog_2...). The Dog-Class has a method called "bark". Further I have an array where I put all my dogs in. I know that dog_0 f.e. is at dogArray[0].

Nopw want dog_3 to bark. I can't call dogArray[2].bark();

Why is that? and how to solve this problem?

Help would be nice thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: accessing methods of objects held in a array

#2 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: accessing methods of objects held in a array

Posted 16 February 2011 - 04:02 AM

Make sure your array type is of Dog. This should work:

public class Dog()
{
    public void Bark()
    { 
    }
}

Dog[] dogs = new Dogs[3];
dogs[0] = new Dog();

dogs[0].Bark();


Was This Post Helpful? 1
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7506
  • View blog
  • Posts: 15,556
  • Joined: 16-October 07

Re: accessing methods of objects held in a array

Posted 16 February 2011 - 05:25 AM

*
POPULAR

When you create an array of objects, the objects aren't initialized. All the values will be null. It's up to you to create the instances that are referenced in the array.

Dog[] dogs = new Dog[2];
dogs[0] = new Dog("Fido");
dogs[0].bark(); // works
dogs[1].bark(); // fails with a null error.  There is a place for object dog, but none has been placed in the house



The idea that initializing an array will also create X number of instances is a common misconception. Not dumb at all.
Was This Post Helpful? 5
  • +
  • -

Page 1 of 1