栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

通过公有的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;
    }
    
    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+"元");
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/238083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号