类定义(课下选做)
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、設計總結
根據題目得要求設計程序,重寫的兩個方法相對比較重要,構造的三個構造方法有兩個沒有用到。
轉載于:https://www.cnblogs.com/zzmzcc/p/10662523.html
總結
- 上一篇: Bing每日壁纸API分享
- 下一篇: 【Qt Tips】QLineEdit内容