构造函数输入未来

时间:2017-09-26 07:02:32

标签: java bluej

class Constr
{
    int a;

    Constr()
    {
        int a=5;;
    }

    public void sd()
    {
        System.out.println(a);
    }

    public static void main()
    {       
        Constr obj=new Constr();
        obj.sd();       
    }
}

当我们运行此代码时,我们得到一个输出:{ 0 }

3 个答案:

答案 0 :(得分:1)

  

int基元的实例变量的默认值设置为0   默认情况下。

现在,在构造函数中,您重新声明变量a而不是将值赋给实例变量,而不是获得所需的输出(即变量a的值应设置为0)。

相反,试试这个:

 class Constr {
  int a;
  Constr() {
   a = 5; // Assigning the value to the instance variable.

  }

  public void sd() {
   System.out.println(a);
  }

  public static void main() {

   Constr obj = new Constr();
   obj.sd();

  }
 }

答案 1 :(得分:0)

下面

window.location.replace("https://stackoverflow.com");

您创建一个新变量,而不是将5分配给您在外部创建的变量。删除声明,只留下Constr(){ int a=5; }

答案 2 :(得分:0)

全局变量和局部变量是不同的。在课堂上,不要初始化" a"是全球性的,构造者是" a"是局部变量。如果需要显示局部变量值5。修改了以下内容。

类Constr {     int a;

Constr()
{
    int a=5;
    this.a = a;
}

public void sd()
{
    System.out.println(a);
}

public static void main()
{       
    Constr obj=new Constr();
    obj.sd();       
}

}