English 中文(简体)
爪哇类成员建筑
原标题:Java class member construction
  • 时间:2012-05-26 03:26:51
  •  标签:
  • java

我只是在从一本看似优秀的书中学习java,但我对其中一个例子有一个问题。在接下来的代码中,我显然遗漏了使用简单阶级成员变量的一步。我做错了什么?

这里的代码是:

class Dog {
    String name;
    String color;
}

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

    Dog [] myDogs = new Dog[3];

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

当我运行此程序时, 它会导致一个无效指针例外, 我给名称成员变量指定一个值 :

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

为什么我不能这么做? Why can I do this?

最佳回答

在 Java 中,当您创建数组时,该数组会自动填入 null 值(除非您使用原始数组,在这种情况下,数组会填充零)。

您正在做的是访问一个无效值, 并试图获取一个域。 您的代码基本上是执行 < code> null. name = " Rover" 。 设置 < code> myDogs[0] 到一个有效的实例, 否则您将获得 NullPointer 例外 。

您可以在此元素中创建一个新的 Dog 实例 :

myDogs[0] = new Dog();

或者你可以做到这一点 当你做阵列,像这样:

Dog[] myDogs = {new Dog(), new Dog(), new Dog()};
问题回答

这是一个空数组, 三个元素长。 它就像排中的三个狗窝, 没有狗。 您必须在每个狗窝中设置一个 < code> dog , 然后再给 < code> dog 命名 :

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

重复 myDogs[1] myDogs[2]

您创建了一个 Dog 类型的数组, 但并未在其中放置任何 Dog 对象 。 Dog [0] 是 null

Dog [] myDogs = new Dog[3];

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

myDogs[0].name = "Rover";




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签