java - 通过构造函数初始化构造函数会产生意外结果吗?

标签 java initialization

从最近几天开始,我对如何通过构造函数初始化实例属性感到困惑。

考虑一下这种情况

class Demo
{
    int a;
    int b;
    Demo(int a,int b)
    {
        this.a*=a;//this produces 0 here 
        this.b*=b;//this produces 0 here
    }
    public static void main(String[] args)
    {
        Demo d1=new Demo(20,30);
        d1.show();
    }
    public void show()
    {
        System.out.println(this.a);
        System.out.println(this.b);
    }
}

这里是如何初始化的。据我所知,构造函数初始化一个值一次。赋值可以进行多次。

最佳答案

整数的初始值为 0。您的实际分配是这样的:

a = 0 * 20

它总是返回 0。

Some documentation :

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

enter image description here

关于java - 通过构造函数初始化构造函数会产生意外结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584990/

相关文章:

c++ - 如何在C++03中实现线程安全的局部静态变量?

Java单例模式

ruby - 在一个类中混合 attr_accessor 和初始化方法

php - 如何在 php 包含文件中设置变量?

java - 计算器错误

java.lang.ClassNotFoundException : org. apache.pdfbox.exceptions.COSVisitorException 异常

java - 关于 future 的好文档/书

java - 插入排序 - 无效的方法声明

c++ - 有哪些不同的初始化方式

java - 关于 Stream - IZ0-809 考试中 OCPJP 8 考试主题中提到的不存在的 merge() 方法