20175234 2018-2019-2 类定义

20175234 2018-2019-2 类定义

题目及要求

  • 设计并实现一个Book类,定义义成Book.java,Book 包含书名,作者,出版社和出版日期,这些数据都要定义getter和setter。定义至少三个构造方法,接收并初始化这些数据。
  • 覆盖(Override)toString方法,返回良好的含有多行的书的描述信息。
  • 覆盖equals方法,书名,作者,出版社和出版日期完全一致才说明两本书是一样的。
  • 创建一个测试类Bookshelf, 其中的main方法创建并更新几个Book对象。Book至少包含三本本学期教材内容。 提交博客,要有设计思路,测试代码和运行结果截图,加上学号水印,要有码云代码链接。

设计思路

  • 实现book中数据的getter和setter

  • 实现 重载toString方法

  • 实现 重载equals方法

重写equals方法的要求:
1、自反性:对于任何非空引用x,x.equals(x)应该返回true。
2、对称性:对于任何引用x和y,如果x.equals(y)返回true,那么y.equals(x)也应该返回true。
3、传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,那么x.equals(z)也应该返回true。
4、一致性:如果x和y引用的对象没有发生变化,那么反复调用x.equals(y)应该返回同样的结果。
5、非空性:对于任意非空引用x,x.equals(null)应该返回false。

  • 实现多种构造方法
    第一种Book(){ }
    第二种 Book(String auther,String publisher,String date){}
    第三种
 Book(String name,String auther,String publisher,String date){
        this.name=name;
        this.auther=auther;
        this.publisher=publisher;
        this.date=date;
}

测试代码

public class Book {
    String name;
    String auther;
    String publisher;
    String date;

    Book(String name,String auther,String publisher,String date){
        this.name=name;
        this.auther=auther;
        this.publisher=publisher;
        this.date=date;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void setAuther(String auther) {
        this.auther = auther;
    }
    public void setPublish(String publish) {
        this.publisher = publish;
    }
    public void setDate(String date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }
    public String getAuther() {
        return auther;
    }
    public String getPublish() {
        return publisher;
    }
    public String getDate() {
        return date;
    }

    public String toString() {
        return  name
                + "  " + auther
                +"  " + publisher
                +"  " + date;
    }

    public boolean equals(Object obj){
        if(this == obj)   //当且仅当 x 和 y 引用同一个对象时,此方法才返回 true;
            return true;
        if(obj == null)
            return false;
        if(getClass()!=obj.getClass())   // 如果两者属于不同的类型,不能相等
            return false;
        if(obj instanceof Book){
            Book book = (Book)obj;
            if(book.name==this.name&&book.auther==this.auther
                    &&book.publisher==this.publisher&&book.date==this.date){
                return true;
            }
        }
        return false;
    }

}

运行截图

码云链接

参考资料

原文地址:https://www.cnblogs.com/ysz-123/p/10667905.html