繁体   English   中英

当我尝试从方法访问它时,为什么我的私有变量变为空?

[英]Why my private variable becomes null when I tried to access it from a method?

我正在尝试访问我在类中生成的字符数组。 但是当我尝试在以下方法中访问此数组时,它变为 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,因为它尚未初始化。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM