1-5的编程题,书名和作业设置为只读,即没有set方法,我怎样设置书名?

1-5的编程题,书名和作业设置为只读,即没有set方法,我怎样设置书名?

请尽量清晰完善地描述问题,以便大家给予专业的回复。

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

3回答
oreooooo 2017-08-19 13:20:09

我在想如果用继承的思想,是不是可以实现将作者和书名封装起来

oreooooo 2017-08-19 13:18:17
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
60
61
62
63
64
65
66
67
68
69
70
class Book{
     //私有属性:书名、作者、出版社、价格
    private String bookName;
    private String author;
    private String press;
    private  double price;
      //通过构造方法实现属性赋值 书名和作者
    public Book(String bookName,String aurhor) {
        this.bookName=bookName;
        this.author=aurhor;
    }
    /*通过公有的get/set方法实现属性的访问,其中:
    1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
    2、限定作者、书名均为只读属性
    */
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        if(price<10) {
            System.out.println("您输入的价格无效。");
            this.price=10.0;
        }else {
            this.price = price;
        }
    }
    //书名只设置为只读
    public String getBookName() {
        return this.bookName;
    }
    //作者只设置为只读
    public String getAuthor() {
        return this.author;
    }
     
     
    public String getPress() {
        return this.press;
    }
    public void setPress(String press) {
        this.press=press;
    }
         
 
     public void infoIntroduction() {
         System.out.println("书名:"+getBookName());
         System.out.println("作者:"+getAuthor());
         System.out.println("出版社:"+getPress());
         System.out.println("价格:"+getPrice()+"元");
          
     }
 
 
}
public class BookTest {
 
    public static void main(String[] args) {
        Book bookCao=new Book("红楼梦","曹雪芹");
        bookCao.setPress("人民出版社");
        bookCao.setPrice(10.0);
        bookCao.infoIntroduction();
        System.out.println("====================");
        Book bookGu=new Book("小李飞刀","古龙");
        bookGu.setPress("中国长安出版社");
        bookGu.setPrice(55.5);
        bookGu.infoIntroduction();
 
    }
 
}

这是助教老师的方法,用构造器传入作者和书名。但我感觉没用用到封装性,外界还是可以通过构造器随便的更改书名和作者。

  • 在new对象的时候必须要给作者和书名赋值的呀,要不然一个赋值的入口都没了。构造器就是new了一个对象,构造器并不是随便更改书名和作者,它的作用是new 出一个对象。
    2017-08-19 23:17:28
好帮手慕雪 2017-07-28 13:54:40

你可在以构造方法中传入书名和作者,然后赋值。祝:学习愉快


问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码