jmoxrox
jmoxrox

Reputation: 13

Java class member construction

I'm just learning java out of a what seems to be an excellent book, but I'm having a problem following one of the examples. In the code that follows, I'm obviously missing a step in using a member variable of a simple class. What am I doing wrong?

Here's the code:

class Dog {
    String name;
    String color;
}

class DogsExample {
    public static void main(String[] args) {

    Dog [] myDogs = new Dog[3];

    myDogs[0].name = "Rover";
    }
}

When I run this program, it causes a null pointer exception where I assign a value to the name member variable:

$ java DogsExample
Exception in thread "main" java.lang.NullPointerException
    at DogsExample.main(DogsExample.java:11)

Why can't I do this?

Upvotes: 1

Views: 122

Answers (3)

WayneC
WayneC

Reputation: 2560

You created an array of the Dog type, but didn't put any Dog objects in it. Dog[0] is null.

Dog [] myDogs = new Dog[3];

myDogs[0] = new Dog(); // <== This populates the array with a new Dog object

myDogs[0].name = "Rover";

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

This is an empty array, three elements long. It's like three kennels in a row, with no dogs in them. You have to put a Dog in each kennel before you can give the Dog a name:

myDogs[0] = new Dog();
myDogs[0].name = "Rover";

Repeat for myDogs[1] and myDogs[2].

Upvotes: 3

Alexis King
Alexis King

Reputation: 43902

In Java, when you create an array, it is automatically filled with null values (unless you are using an array of primitives, in which case the array is filled with zeros).

What you are doing is accessing a null value and trying to get a field of it. Your code is essentially performing null.name = "Rover". Set myDogs[0] to a valid instance, or you'll get a NullPointerException.

You can create a new instance of Dog in the element like this:

myDogs[0] = new Dog();

Or you can do it when you make the array, like this:

Dog[] myDogs = {new Dog(), new Dog(), new Dog()};

Upvotes: 2

Related Questions