Java 为什么我的私有变量在尝试从方法访问它时变为null?

Java 为什么我的私有变量在尝试从方法访问它时变为null?,java,Java,我试图访问在类中生成的字符数组。但是当我试图用下面的方法访问这个数组时,它会变成null。我该如何解决这个问题 public class DnaSequence { private char[] dna; public DnaSequence(char[] dna) { /** * I generated my dna array here and has been tested */ } public int length() {

我试图访问在类中生成的字符数组。但是当我试图用下面的方法访问这个数组时,它会变成null。我该如何解决这个问题

public class DnaSequence {

  private char[] dna;

  public DnaSequence(char[] dna) {
    /**
      * I generated my dna array here and has been tested
      */
  }

  public int length() {
    /**
      * This is the part I'm trying to access that array but got a null
      */
    return dna.length;
  }
}
这是我使用的测试代码:

public class DnaSequenceTest {

  public static void main(String[] args) {

    char[] bases = { 'G', 'A', 'T', 'T', 'A', 'C', 'A' };
    DnaSequence seq = new DnaSequence(bases);

    int test = seq.length();
    System.out.println(test);
  }
}

并得到一个空指针异常

如果在构造函数中没有为
this.dna赋值,它将永远不会从
null更改其值

dna
(开头省略
this.
)的任何引用都是引用传递给构造函数的参数,而不是引用
dna
实例变量

public DnaSequence(char[] dna) {
 /**
   * I generated my dna array here and has been tested
   */
   this.dna = ... // You need to assign to see it, probably this.dna = dna;
                  // that will set the dna instance variable equals 
                  // to the dna parameter passed calling the constructor
}

我认为你搞乱了变量的范围

问题是dna变量的范围

在函数DnaSequence(char[]dna)中,使用了与上面声明的不同的dna变量

类内部(方法上方)声明的变量称为实例变量,其中方法内部的变量称为局部变量。 如果要访问与局部变量同名的实例变量,则需要使用“this”关键字

例如:

public class DnaSequence {

private char[] dna; //Instance Variable

public DnaSequence(char[] dna) {  // Local Variable
/**
  * I generated my dna array here and has been tested
  */
  System.out.println(dna); // Will access the local variable
  System.out.println(this.dna); // Will access the instance variable
}

public int length() {
/**
  * This is the part I'm trying to access that array but got a null
  */
return dna.length; // Will access the instance variable
}
}
所以如果没有这个关键字,如果你正在访问dna,它不会更新你的实例变量,我想你应该更新它。
因此它将打印空值,因为它尚未初始化。

问题是我创建了您描述的字段(字符串对象),然后在我的构造函数中,我没有给私有变量赋值,而是再次使用字符串关键字,基本上重新创建了变量


检查你的构造函数,看看你是否初始化了两次

请发布构造函数的内容或更改代码的格式。。另外,您确定没有从构造函数生成本地数组吗?因为它在创建时为null,并且您从未更改过它。您是否在构造函数中将您的dna私有成员称为“this.dna”?否则,您正在操作参数,而不是您的私人成员。请尝试
this.dna=dna
您好,欢迎使用SO!请阅读,并添加代码片段可能会有所帮助。