用java语言编写在包xhu.soft中定义一个教材类,包含编号、书名、作者、出版社和价格等属性,要求能用构造方法初始化图书 信息;同时能修改图书的各信息。然后在包xhu.test包中编写图书的测试类,输出图书信息。
时间: 2024-09-28 14:10:11 浏览: 40
在Java中,我们首先会在`xhu.soft`包下定义一个名为`Book`的类,它将包含图书的基本信息:
```java
package xhu.soft;
public class Book {
private String bookId;
private String title;
private String author;
private String publisher;
private double price;
// 构造方法,用于初始化图书信息
public Book(String bookId, String title, String author, String publisher, double price) {
this.bookId = bookId;
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
// getter和setter方法
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
```
接着,在`xhu.test`包下的`BookTest`类中,我们将测试`Book`类的功能:
```java
package xhu.test;
import xhu.soft.Book;
public class BookTest {
public static void main(String[] args) {
// 创建一个新的Book实例
Book book1 = new Book("001", "Java编程入门", "张三", "人民邮电出版社", 59.9);
// 输出初始信息
System.out.println("Book ID: " + book1.getBookId());
System.out.println("Title: " + book1.getTitle());
System.out.println("Author: " + book1.getAuthor());
System.out.println("Publisher: " + book1.getPublisher());
System.out.println("Price: " + book1.getPrice());
// 修改信息并再次输出
book1.setTitle("Java高级编程");
book1.setPrice(79.9);
System.out.println("\nModified Information:");
System.out.println("Title: " + book1.getTitle());
System.out.println("Price: " + book1.getPrice());
}
}
```
在这个例子中,我们在`BookTest`中创建了一个`Book`对象,设置了初始信息并输出,然后又更改了部分信息并再次展示了结果。
阅读全文