java参数作用,Java中参数化构造函数的用途是什么?

本文解释了为什么在Java中应该使用参数化构造器而不是默认构造器。默认构造器会将对象属性初始化为默认值(如0或false),而参数化构造器允许你在创建对象时立即设置属性值,并提供了执行额外初始化代码的灵活性。通过使用自定义构造器,你可以更好地控制对象的状态并确保其正确初始化。
摘要由CSDN通过智能技术生成

Im a beginner in java and i wanted to know in a simple way why you should use a parameterized constructor instead of a default one provided by the compiler.

Thanks

解决方案

By the default constructor any attributes your object might have are set to 0, false et cetera. If you want to set the attributes right away you can use a parameterized constructor. Also using you own constructor of course gives you the option of executing code before the object (technically while) is created.

By the way: The answer that "the default won't set any value to the properties" is wrong. For example this code:

public class Test {

private int test;

private boolean test2;

public static void main(String[] args) {

Test test = new Test();

System.out.println(test.test);

System.out.println(test.test2);

}

}

Will print out "0" and "false".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值