1、设计思路
1.根据题目要求覆盖(Override)toString方法、覆盖equals方法,即重写这两个方法;
2.根据题目要求定义至少三个构造方法,接收并初始化这些数据;
3.创建一个测试类Bookshelf, 其中的main方法创建并更新几个Book对象,并对产生的对象进行测试。
2、设计代码
Book.java
public class Book {String name;String writter;String publish;String date;Book(){ //定义第一个构造方法将所有元素初始化name=null;writter=null;publish=null;date=null;}Book(String name,String writter,String publish,String date){ //定义第二种构造方法给所有元素赋值this.name=name;this.writter=writter;this.publish=publish;this.date=date;}Book(String book[]){ //定义第三种构造方法用数组给元素赋值this.name=book[0];this.writter=book[1];this.publish=book[2];this.date=book[3];}public void setName(String name){this.name=name;}public String getName(){return name;}public void setWritter(String writter){this.writter=writter;}public String getWritter(){return writter;}public void setPublish(String publish){this.publish=publish;}public String getPublish(){return publish;}public void setDate(String date){this.date=date;}public String getDate(){return date;}public String toString(){ //重写toString()方法return "书名:"+name+",作者:"+writter+",出版社:"+publish+",出版日期:"+date;}public boolean equals(Object x){ //重写equals()方法if(this==x) //判断地址是否相等return true;if(x==null) //判断对象是否为空return false;if (getClass()!=x.getClass()) //判断对象类型是否相等return false;Book book = (Book)x; //上转型对象,判断子类成员变量是否相等if(book.name==this.name&&book.writter==this.writter&&book.publish==this.publish&&book.date==this.date)return true;elsereturn false;}
}
BookShelf.java
import java.util.*;
public class BookShelf {public static void main(String[] args){Book b0=new Book("Java","耿祥义","清华大学出版社","2017");Book b1=new Book("汇编语言与程序设计","钱晓捷","电子工业出版社","2018");Book b2=new Book("密码学","郑秀林","金城出版社","2016");Scanner reader=new Scanner(System.in);String s=null;System.out.println("进入书柜,请输入书名:");s=reader.nextLine();if(s.equals("Java")){System.out.println(b0);System.out.println(b0.equals(b0));}else if(s.equals("汇编语言与程序设计")){System.out.println(b1);System.out.println(b1.equals(b1));}else if(s.equals("密码学")){System.out.println(b2);System.out.println(b2.equals(b2));}else{System.out.println("书柜中无此书籍!");System.out.println(b0.equals(b2));}}
}
3、运行截图
4、码云链接
https://gitee.com/zzm-zcc/zhang_zhi_min/tree/master/%E7%B1%BB%E5%AE%9A%E4%B9%89
5、设计总结
根据题目得要求设计程序,重写的两个方法相对比较重要,构造的三个构造方法有两个没有用到。