Java默认构造函数
时间:2020-02-23 14:34:59 来源:igfitidea点击:
在本教程中,我们将看到Java默认构造函数。
Default constructor是没有参数的构造函数,由编译器插入,除非我们明确地提供任何其他构造函数。
我们将无法看到它,因为它存在于类文件中而不是源文件中。
没有参数构造函数和默认构造函数之间有什么区别吗?
如果我们在类中提供任何构造函数,则它不再是默认构造函数。
有很多关于它的辩论,但这是我的意见。
当我们没有提供任何构造函数时,编译将插入默认构造函数,该构造函数将调用超级类的默认构造函数。
我们需要确保超级类有NO-ARG构造函数。
让我们在一个示例的帮助下创建一个名为person.java的类
package org.igi.theitroad.constructor;
public class Person {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建另一个名为employee.java的类
package org.igi.theitroad.constructor;
public class Employee extends Person {
int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
我们将使用此消息进行编辑错误。
"隐式超级构造函数 Person()默认构造函数未定义。
必须定义一个显式构造函数"如我们所见,它告诉我们,该人类应该具有显式构造函数,否则它不会编译。
一旦添加arg构造函数 Person类,我们不会再获取编译错误。
package org.igi.theitroad.constructor;
public class Person {
String name;
int age;
//Added explicit constructor
public Person()
{
System.out.println("Added explicit constructor");
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
正如我们可以看到将显式构造函数添加到Person类后,员工程序中不会有任何编译错误。

