在Java中,构造函数(Constructor)的重载(Overloading)和覆盖(Overriding)是两个不同的概念,它们在面向对象编程中扮演着不同的角色。下面分别解释这两个概念及其区别:
例如:
class Person {
String name;
int age;
// 构造函数重载
Person() {
this("Unknown", 0);
}
Person(String name) {
this(name, 0);
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
例如:
class Person {
String name;
int age;
// 父类构造函数
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
String school;
// 构造函数覆盖
Student(String name, int age, String school) {
super(name, age); // 调用父类构造函数
this.school = school;
}
}
总结: