类定义(课下选做)
一、设计思路
- 之前在课上做过类似的题目,首先分析,这个题的重点在重写toString类和equals类
- 首先,是toString类,直接重写
public String toString(){return 字符串;}
返回要输出的字符串即可 - 然后是equals类
- 用
public boolean equals(Object o){内容}
重写 - 先用
if(this==o)
判断地址是否相同,若相同直接true - 再用
if(o==null)
判断对象是否为空 - 接着用
if (getClass()!=o.getClass())
判断对象类型是否相等 - 最后判断成员变量是否相等
- 为提高程序效率,应重写hasCode方法
- 用
二、代码
Book.java
public class Book {
String name;
String auther;
String publish;
String date;
Book(){}
Book(String name){}
Book(String auther,String publish,String date){}
Book(String name,String auther,String publish,String date){
this.name=name;
this.auther=auther;
this.publish=publish;
this.date=date;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAuther(String auther){
this.auther=auther;
}
public String getAuther(){
return auther;
}
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+",作者:"+auther+",出版社:"+publish+",出版日期:"+date;
}
public boolean equals(Object o){
if (this==o) //判断地址是否相等,若相等,直接返回true
return true;
if (o==null) //判断对象是否为空
return false;
if (getClass()!=o.getClass()) //判断对象类型是否相等
return false;
Book book=(Book)o; //向下转型,判断成员变量是否相等
if (book.name==this.name&&book.auther==this.auther&&book.publish==this.publish&&book.date==this.date)
return true;
else
return false;
}
public int hashCode() { //重写hasCode类,提高程序效率
int result = name.hashCode();
result = 31 * result + auther.hashCode();
result = 31 * result + publish.hashCode();
result = 31 * result + date.hashCode();
return result;
}
}
bookShelf.java
public class bookShelf {
public static void main(String[] args){
Book b0 = new Book("Java","耿祥义","清华大学出版社","2017.9");
Book b1 = new Book("汇编语言与程序设计","钱晓捷","电子工业出版社","2018.6");
Book b2 = new Book("计算机网络","谢希仁","电子工业出版社","2017.1");
System.out.println(b0);
System.out.println(b1);
System.out.println(b2);
System.out.println(b0.getName());
System.out.println(b1.getAuther());
System.out.println(b2.getDate());
System.out.println(b0.equals(b1));
System.out.println(b2.equals(b2));
}
}
三、补充改正
- 经老师提示,在输出结果时,直接
println(对象名)
就能调用toString,不用再明显的写出来。