Java2024/src/chapter3/Example05.java
2024-10-10 09:19:56 +08:00

64 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chapter3;
class Book {
int id; // 编号
String name; // 书名
// public Book() {
// this.id = 0;
// this.name = "未命名";
// System.out.println("初始化:无参构造被调用!");
// }
// public Book(int id, String name) {
// this.id = id;
// }
// 打印信息
public void print() {
System.out.println("print函数 - ID" + this.id + ",书名:" + this.name);
}
// 获取书号
public int getId() {
return id;
}
// 设置书号
public void setId(int id) {
this.id = id;
}
// 获取书名
public String getName() {
return name;
}
// 设置书名
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Book[] books = new Book[10];
// 使用 setter 初始化
books[0] = new Book();
books[0].print();
System.out.println("初始化:手动");
books[0].setId(1);
books[0].setName("Java教程");
books[0].print();
System.out.println("============");
// 直接访问属性进行初始化(注意访问控制)
books[1] = new Book();
books[1].print();
System.out.println("初始化:手动");
books[1].id = 2;
books[1].name = "JSP教程";
books[1].print();
}
}