Java定义一个Book类,包含书名____、作者____和出版年份____。编写一个构造方法,并使用该方法创建Book对象时自动设置出版年份为当前年份
时间: 2024-10-02 18:01:53 浏览: 43
在Java中,你可以定义一个名为`Book`的类,它有三个属性分别代表书名、作者和出版年份。以下是这个类的基本定义,包括一个构造方法来设置默认的出版年份:
```java
public class Book {
private String title; // 书名
private String author; // 作者
private int publicationYear; // 出版年份
// 构造方法,使用当前年份作为默认出版年份
public Book(String title, String author) {
this.title = title;
this.author = author;
this.publicationYear = Calendar.getInstance().get(Calendar.YEAR); // 获取当前年份
}
// 提供getter和setter方法,这里省略了
// 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 int getPublicationYear() { return publicationYear; }
// public void setPublicationYear(int publicationYear) { this.publicationYear = publicationYear; }
// 如果需要,可以添加其他方法,如展示书籍信息等
public void displayBookInfo() {
System.out.println("书名: " + title);
System.out.println("作者: " + author);
System.out.println("出版年份: " + publicationYear);
}
}
```
然后,你可以这样创建并显示一个`Book`对象:
```java
public static void main(String[] args) {
Book myBook = new Book("Java编程思想", "Bruce Eckel");
myBook.displayBookInfo();
}
```
阅读全文
相关推荐


















