封装小案例

1.以面向对象的思想,编写自定义类描述图书信息。设定属性包括:书名,作者,出版社名,价格;方法包括:信息介绍

2.要求:

  1. 设置属性的私有访问权限,通过公有的get,set方法实现对属性的访问
  2. 限定介格必须大于10,如果无效进行提示
  3. 设计构造方法实现对属性赋值
  4. 信息介绍方法描述图书所有信息
  5. 编写测试类,测试图书类的对象及相关方法(测试数据信息自定)

3.源码 

public class Book {
    private String bookname;
    private String author;
    private String publish;
    private double price;


    public void setPrice(double price) {
        if (price < 10) {
            System.out.println("价格无效,已修改默认值");
            this.price = 10.0;
        } else {
            this.price = price;
        }
    }

    public Book(String bookname, String author, String publish, double price) {
        this.bookname = bookname;
        this.author = author;
        this.publish = publish;
        this.setPrice(price);
    }
    /**
     * 显示图书信息
     */
    public void introduce() {
        System.out.println("书名:" + bookname);
        System.out.println("作者:" + author);
        System.out.println("出版社:" + publish);
        System.out.println("价格:" + price + "元");
    }
}

测试类

public class BookTest {
    public static void main(String[] args) {
        Book book=new Book("鹿鼎记","金庸","人民文学出版社",9.0);
        book.introduce();
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值