day06-面向对象的案例

This commit is contained in:
2026-05-10 16:23:59 +08:00
parent 8526e31417
commit c4b089a048
2 changed files with 114 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
package com.inmind.test04;
public class Book {
//属性
private String id;
private String name;
private double price;
private String publishDate;
//无参构造方法
public Book() {
}
//满参构造方法
public Book(String id, String name, double price, String publishDate) {
this.id = id;
this.name = name;
this.price = price;
this.publishDate = publishDate;
}
//get/set方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
//自定义showBook方法
public void showBook() {
System.out.println("图书编号:" + this.id + ",图书名称:" + this.name + ",图书价格:"
+ this.price + ",出版日期:" + this.publishDate);
}
}

View File

@@ -0,0 +1,53 @@
package com.inmind.test04;
import com.inmind.constructor03.Cat;
import com.inmind.private02.Student;
/*
* 定义一个图书Book类。
- 属性:图书编号,书名,价格,出版日期
- 构造方法:
- 无参构造方法,满参构造方法
- 成员方法:
- get/set方法
- showBook方法输出图书信息
* 定义测试类,使用满参构造方法,创建三(多)个Book对象判断价格最贵的图书存放书的数组的遍历并输出图书信息。
*/
public class Test06 {
public static void main(String[] args) {
//创建三个图书对象
Book b1 = new Book("b001", "java从入门到入土", 9.0, "2026-01-01");
Book b2 = new Book("b003", "mysql从删库到跑路", 99.0, "2026-02-01");
Book b3 = new Book("b005", "Linux操作系统", 9.9, "2026-01-01");
//定义一个数组,存放图书对象
/*Book[] books = new Book[3];//动态初始化创建一个长度为3的存放book对象的数组
books[0] = b1;
books[1] = b2;
books[2] = b3;*/
//Book[] books = new Book[]{b1,b2,b3};//静态初始化
Book[] books = {b1,b2,b3};//静态初始化简写形式
//可以找出最贵的书对象&&也可以直接找出最贵的索引(遍历操作||if-else
//定义出一个变量,记录最贵的书对象
// Book maxPriceBook = books[0];
int maxIndex = 0;
//遍历判断,找出最贵的书对象
for (int i = 1; i < books.length; i++) {
//根据索引获取当前遍历的元素
Book book = books[i];
Book maxBook = books[maxIndex];
if (book.getPrice() > maxBook.getPrice()) {
maxIndex = i;
}
}
//输出最贵图书信息。
// maxPriceBook.showBook();
books[maxIndex].showBook();
}
}