java编写一个book类
时间: 2024-02-03 11:12:28 浏览: 65
java Book类
下面是一个Java编写的Book类的示例:
```java
public class Book {
private String title;
private String author;
private int year;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setYear(int year) {
this.year = year;
}
@Override
public String toString() {
return title + " by " + author + ", published in " + year;
}
}
```
这个类包含三个私有属性(书名、作者和出版年份)以及三个公有方法来获取或设置这些属性。toString() 方法被重载,以便在控制台上输出一个可读的字符串表示形式。在构造函数中初始化这些属性,并在需要时提供了 setter 和 getter 方法。
阅读全文