可以使用以下代码创建一个具有name、price、author和country属性的Java图书类Book2:
public class Book2 {
private String name;
private double price;
private String author;
private String country;
public Book2(String name, double price, String author, String country) {
this.name = name;
this.price = price;
this.author = author;
this.country = country;
}
// Getters and setters for each attribute
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 getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
这个类中有一个构造函数,它可以用来初始化对象的属性。还有一些getter和setter方法,用于访问和修改属性值。
更详细的回复
要创建一个Java图书类Book2,可以使用以下代码实现:
public class Book2 {
private String name;
private double price;
private String author;
private String country;
public Book2(String name, double price, String author, String country) {
this.name = name;
this.price = price;
this.author = author;
this.country = country;
}
// getter and setter methods for all the attributes
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 getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
这里我们定义了四个属性:name表示书名,price表示价格,author表示作者,country表示国家。我们在构造方法中初始化对象的属性值,并提供了每个属性的getter和setter方法来访问和修改这些属性。
例如,我们可以使用以下代码创建一个Book2对象并设置其属性值:
Book2 book = new Book2("The Great Gatsby", 10.99, "F. Scott Fitzgerald", "USA");
book.setPrice(9.99);
System.out.println(book.getName()); // Output: The Great Gatsby
System.out.println(book.getAuthor()); // Output: F. Scott Fitzgerald
System.out.println(book.getPrice()); // Output: 9.99
System.out.println(book.getCountry()); // Output: USA
这里我们创建了一个名为book的Book2对象,并设置了其属性值。接着,我们使用setter方法将其价格修改为9.99,并使用getter方法分别获取了书名、作者、价格和国家属性的值,并打印输出。