默认构造函数的目的是为对象分配默认值。 如果类中没有构造函数,java 编译器会隐式创建默认构造函数。
class Student3 {
int id;
String name;
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
Student3 s1 = new Student3();
Student3 s2 = new Student3();
s1.display();
s2.display();
}
}
运行结果:
0 null
0 null
说明 :在上面的类中,没有创建任何构造函数,因此编译器提供了一个默认构造函数。 这里 0
和 null
值由默认构造函数提供。