20175221曾祥杰 类定义
20175221曾祥杰 类定义
题目要求
- 设计并实现一个Book类,定义义成Book.java,Book 包含书名,作者,出版社和出版日期,这些数据都要定义getter和setter。定义至少三个构造方法,接收并初始化这些数据。覆盖(Override)toString方法,返回良好的含有多行的书的描述信息。覆盖equals方法,书名,作者,出版社和出版日期完全一致才说明两本书是一样的。
- 创建一个测试类Bookshelf, 其中的main方法创建并更新几个Book对象。Book至少包含三本本学期教材内容。
- 提交博客,要有设计思路,测试代码和运行结果截图,加上学号水印,要有码云代码链接。
- 独立完成,抄袭倒扣分
设计思路
- 按照要求对书的数据分别定义getter和setter
- 覆盖(Override)toString方法,返回书的描述信息
- 覆盖equals方法,说明两本书是否一样
- 创建测试类Bookshelf
核心代码
public class Book { private String bookname; private String writer; private String publishing; private String publishingdate; //定义getter public String getBookname() {//返回书名 return bookname; } public String getWriter() {//返回作者 return writer; } public String getPublishing() {//返回出版社 return publishing; } public String getPublishingdate() {//返回出版日期 return publishingdate; } //定义setter public void setBookname(String bookname) { this.bookname = bookname; } public void setWriter(String writer) { this.writer = writer; } public void setPublishing(String publishing) { this.publishing = publishing; } public void setpublishingdate(String publishingdate) { this.publishingdate = publishingdate; } //注入string属性 public Book(String bookname, String writer, String publishing, String publishingdate) { this.bookname = bookname; this.writer = writer; this.publishing = publishing; this.publishingdate = publishingdate; } //覆盖toString方法 public void toString(Book book) { System.out.println("bookname:"+book.getBookname()); System.out.println("writer:"+book.getWriter()); System.out.println("publishing:"+book.getPublishing()); System.out.println("publishingdate:"+book.getPublishingdate()); } //覆盖equals方法 public boolean equals(Object o) {//比较两本书是否一致,一致返回true,反之返回false if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; if (bookname != null ? !bookname.equals(book.bookname) : book.bookname != null) return false; if (writer != null ? !writer.equals(book.writer) : book.writer != null) return false; if (publishing != null ? !publishing.equals(book.publishing) : book.publishing != null) return false; return publishingdate != null ? publishingdate.equals(book.publishingdate) : book.publishingdate == null; } }
运行截图
代码托管(https://gitee.com/zxjacdl/zxj175221/tree/master/ldy)
参考资料:
Object o 与 Object o = null 的区别(https://zhidao.baidu.com/question/124299247.html)
java 中覆盖 equals() 方法 (https://blog.csdn.net/weixiankui1997/article/details/79436392)
java中getClass()方法简介 (https://blog.csdn.net/expect521/article/details/79139829)