exercise_3.md 1.4 KB
Newer Older
Y
Yuan Yuan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
# 题目3

实现一个方法`public Book(int id, String bookName, BookType type, int pages, double price);`,作用是使用方法中的参数初始化对象的属性,注意参数没有borrowTimes属性,对象的borrowTimes属性直接设置成0。

提示:如果担心id冲突,可以使用`this.id=id;`这样的写法,this代表对象本身


## 答案

```java
public class Book {
    private int id;
    private String bookName;
    private BookType type;
    private int borrowTimes;
    private int pages;
    private double price;

    public Book(int id, String bookName, BookType type, int pages, double price) {
        this.id = id;
        this.bookName = bookName;
        this.type = type;
        this.pages = pages;
        this.price = price;
        this.borrowTimes = 0;
    }

    public int getId() {
        return id;
    }

    public String getBookName() {
        return bookName;
    }

    public BookType getBookType() {
        return type;
    }

    public int getBorrowTimes() {
        return borrowTimes;
    }

    public int getPages() {
        return pages;
    }

    public double getPrice() {
        return price;
    }
}

```

## 选项

## 补充
这类方法,在Java中,我们一般称之为**构造方法**,这类方法的前面没有public/private这样的关键字,**方法名也只能是类名**,在新建一个该类的对象时会自动调用该方法完成对对象的初始化。