ITPub博客

首页 > IT职业 > IT图书 > Java 面向对象封装的代码练习

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

IT图书 作者:usli 时间:2021-09-09 10:48:32 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+"元");
    }

}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3324/viewspace-2826327/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-14

  • 博文量
    89
  • 访问量
    808