【问题标题】:constructor is not called when i create obj variables创建 obj 变量时不调用构造函数
【发布时间】:2016-12-01 21:36:23
【问题描述】:
class add{

add(){
    int a=0;
    int b=0;
}
void display()
{ int s;
    s=a+b;
    System.out.println(s);
}
}
class main{
        public static void main(String arg[])
      {
            add so=new add();
            so.display();
           }

}

当我运行时,它显示 a,b 未定义,而 s 已定义。 当 display() 函数正常工作时,不会调用默认构造函数。

显然我是在构造函数中声明变量。因此它对我不起作用。

【问题讨论】:

  • 因为ab 是构造函数的本地变量,因此无法从display() 访问
  • ab 是构造函数中的局部变量。当构造函数完成时,它们会被移除。
  • 你怎么能运行它呢?这甚至不应该编译。
  • 这完全坏了。而且你没有调用构造函数的“事实”可能有点错误。
  • 我正在输入一个答案,但我真正想到的是这是一个非常糟糕的代码示例,必须完全改变它才能完全正确。

标签: java class object methods constructor


【解决方案1】:

您的代码不起作用,因为ab 是构造函数的局部变量。因此,它们无法在构造函数之外访问。

使用以下代码解决您的问题。

class Main{
    public static void main(String[] args)
    {
        Add so=new Add();
        so.display();
    }
}

class Add{
    int a, b;

    Add(){
        a=0;
        b=0;
    }

    void display()
    {
        int s;
        s=a+b;
        System.out.println(s);
    }
}

并对类名使用 java 命名约定。

【讨论】:

    【解决方案2】:
    class add{
     int a;
     int b;
    
    add(){
    
    }
    void display()
    { int s;
        s=a+b;
        System.out.println(s);
    }
    }
    class main{
            public static void main(String arg[])
          {
                add so=new add();
                so.display();
               }
    

    这样做。使 ab 可用于显示方法。 ab 将在构造函数被调用时自动初始化为 0
    您正在做的是在构造函数中声明 ab 。 所以他们的范围将取决于构造函数。

    【讨论】:

    • 如果您给出一个示例作为答案,请至少遵循命名约定。
    • 这不是我自己写的。我刚刚纠正了主要的事情。@eldo
    猜你喜欢
    • 2012-01-23
    • 2013-03-07
    • 2019-07-25
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多