- 构造方法基本特点:
- 构造方法的名称必须与类名相同。
- 构造方法没有返回类型,包括void。
- 构造方法可以有参数,这些参数用于初始化对象的属性。
- 每个类都可以有一个或多个构造方法,可以重载构造方法,即在同一个类中可以定义多个构造方法,只要它们的参数列表不同。
示例代码:
public class Person {
private String name;
private int age;
// 无参构造方法
public Person() {
this.name = "Unknown";
this.age = 0;
}
// 带参数的构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 其他方法和属性的定义
}
- 默认构造方法:
- 如果没有显式定义构造方法,Java会为类提供一个默认的无参构造方法。
- 如果您显式定义了任何构造方法,Java将不再提供默认构造方法。
示例代码:
public class Student {
private String name;
private int age;
// 没有显式定义构造方法,但仍有默认的无参构造方法
// 其他方法和属性的定义
}
- 构造方法的重载:
- 可以在同一个类中定义多个构造方法,只要它们的参数列表不同。这被称为构造方法的重载。
- 构造方法的重载允许您以不同的方式初始化对象,根据不同的参数提供不同的初始化选项。
示例代码:
public class Book {
private String title;
private String author;
// 无参构造方法
public Book() {
this.title = "Unknown Title";
this.author = "Unknown Author";
}
// 带参数的构造方法
public Book(String title) {
this.title = title;
this.author = "Unknown Author";
}
// 带两个参数的构造方法
public Book(String title, String author) {
this.title = title;
this.author = author;
}
// 其他方法和属性的定义
}
- 调用其他构造方法:
- 在构造方法中,可以使用
this()
来调用本类的其他构造方法,或使用super()
来调用父类的构造方法。这通常用于避免代码重复,确保在对象初始化时执行共同的逻辑。
- 在构造方法中,可以使用
示例代码:
public class Rectangle {
private int width;
private int height;
// 无参构造方法
public Rectangle() {
this(1, 1); // 调用带两个参数的构造方法
}
// 带两个参数的构造方法
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// 其他方法和属性的定义
}