继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java 面向对象封装的代码练习

慕婉清_林杰克
关注TA
已关注
手记 1
粉丝 0
获赞 0

私有属性:书名、作者、出版社、价格

通过公有的get/set方法实现属性的访问,其中:

  1. 限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
  2. 限定作者、书名均为只读属性

图片描述

public class BookTest {

     // 测试方法
	 public static void main(String[] args) {
      //实例化对象,调用相关方法实现运行效果
        Book bk = new Book("红楼梦","曹雪芹");
        bk.setPress("人民文学出版社");
        bk.setPrice(10);
        bk.showInfo();
        System.out.println("===============");
        Book bk2 = new Book("小李飞刀","古龙");
        bk2.setPress("中国长安出版社");
        bk2.setPrice(55.5);
        bk2.showInfo();
     }
}
public class Book {
  //私有属性:书名、作者、出版社、价格
    private String name,author,press;
    private double price;
  //通过构造方法实现属性赋值
    public Book(){
        
    }
    public Book(String name,String author){
        this.name = name;
        this.author = author;
    }
    /*通过公有的get/set方法实现属性的访问,其中:
    1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
    2、限定作者、书名均为只读属性
    */
    public void setPress(String press){
        this.press = press;
    }
    public void setPrice(double price){
        if(price<=10){
            this.price=10;
            System.out.println("图书价格最低10元");
        }
        else
            this.price = price;
    }
    public String getName(){
        return name;
    }
    public String getAuthor(){
        return author;
    }
    public String getPress(){
        return press;
    }
    public double getPrice(){
        return price;
    }
  //信息介绍方法,描述图书所有信息
    public void showInfo(){
        System.out.println("书名:"+this.name);
        System.out.println("作者:"+this.author);
        System.out.println("出版社:"+this.press);
        System.out.println("价格:"+this.price+"元");
    }

}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP