老师我这么做,代码思路正确吗?
来源:1-7 编程练习
weixin_慕码人71622
2020-03-10 15:49:56
public class BookTest { // 测试方法 public static void main(String[] args) { //实例化对象,调用相关方法实现运行效果 Book one=new Book("红楼梦","曹雪芹","人民文学出版社"); one.setPrice(9); one.smsBook(); System.out.println("===================================="); Book two=new Book("小李飞刀","古龙","中国长安出版社"); two.setPrice(55.5); two.smsBook(); } }
public class Book { //私有属性:书名、作者、出版社、价格 private String title; private String author; private String press; private double price; //通过构造方法实现属性赋值 /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public void setPrice(double price){ if(price<10){ System.out.println("图书价格最低10元"); price=10; this.price=price; }else{ this.price=price; } } Book(String title,String author,String press){ this.title=title; this.author=author; this.press=press; } public String getTitle(){ return title; } public String getAuthor(){ return author; } //信息介绍方法,描述图书所有信息 public void smsBook(){ System.out.println("书名:"+title); System.out.println("作者:"+author); System.out.println("出版社"+press); System.out.println("价格"+price); } }
1回答
同学你好,思路正确,写的很棒哦~
但是有一点需要优化:
建议你添加出版社的get,set方法。价格的get方法
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
相似问题