问题描述
我是Java的初学者,我想以一种简单的方式知道为什么您应该使用参数化构造函数而不是编译器提供的默认构造函数.
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.
谢谢
推荐答案
通过默认构造函数,对象可能具有的所有属性都将设置为0,false等.如果要立即设置属性,则可以使用参数化的构造函数.当然,也可以使用您自己的构造函数为您提供在创建对象(技术上是在创建对象之前)之前执行代码的选项.
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);
}
}
将打印出"0"和"false".
Will print out "0" and "false".
这篇关于Java中参数化构造函数的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!