构造方法重载
本课属于 Coddy Java 学习旅程的“面向对象编程”单元。第 8 课,共 87 课。
构造函数重载是指定义多个参数列表不同的构造函数。使用 this() 从一个构造函数调用另一个构造函数。
多个构造函数
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this.title = title;
this.author = author;
this.pages = 0;
}
}使用 this() 进行构造函数链式调用
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this(title, author, 0); // 调用有 3 个参数的构造函数
}
public Book() {
this("Unknown", "Unknown"); // 调用有 2 个参数的构造函数
}
}用法
Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();this() 必须是构造函数中的第一条语句。构造函数链可以避免在多个构造函数中重复赋值逻辑。
挑战
中等使用构造函数链,为 Product 类创建三个重载构造函数:
- 3 个参数的构造函数:name、price、stock
- 2 个参数的构造函数:name、price(stock 默认为 0)
- 默认构造函数:不带参数(name = "Unknown",price = 0,stock = 0)
使用 this() 链接构造函数,避免代码重复。
亲手试试
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
double price = Double.parseDouble(scanner.nextLine());
int stock = Integer.parseInt(scanner.nextLine());
Product product1 = new Product(name, price, stock);
Product product2 = new Product("Keyboard", 79.99);
Product product3 = new Product();
System.out.println("Product 1: " + product1.getName() + " - $" + product1.getPrice() + " (Stock: " + product1.getStock() + ")");
System.out.println("Product 2: " + product2.getName() + " - $" + product2.getPrice() + " (Stock: " + product2.getStock() + ")");
System.out.println("Product 3: " + product3.getName() + " - $" + product3.getPrice() + " (Stock: " + product3.getStock() + ")");
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: Java 在线编译器