gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:15:11 25 4
gpt4 key购买 nike

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

考虑一下这种情况

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com