帮我看看有什么需要简化和修改的地方,谢谢~
package com.imooc.animal;
public class Book {
//私有属性:书名、作者、出版社、价格
private String name;
private String author;
private String press;
private float price;
//通过构造方法实现属性赋值
public Book(String name,String author,String press,float price) {
this.setName(name);
this.setAuthor(author);
this.setPress(press);
this.setPrice(price);;
}
public Book() {
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
if(price<10) {
System.out.println("图书价格必须大于10元!");
this.price=10;
}
else {
this.price = price;
}
}
public void setAuthor(String author) {
this.author = author;
}
public void setName(String name) {
this.name=name;
}
//信息介绍方法,描述图书所有信息
public void bookIntro() {
System.out.println("书名:"+this.name);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.getPress());
System.out.println("价格:"+this.getPrice()+"元");
}
}================================================================
package com.imooc.animal;
public class BookTest {
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
System.out.println("图书价格最低10元");
Book bk1=new Book();
bk1.setName("红楼梦");
bk1.setAuthor("曹雪芹");
bk1.setPress("人民文学出版社");
bk1.setPrice(10);
bk1.bookIntro();
System.out.println("====================================");
Book bk2=new Book();
bk2.setName("小李飞刀");
bk2.setAuthor("古龙");
bk2.setPress("中国长安出版社");
bk2.setPrice(55.5f);
bk2.bookIntro();
}
}39
收起
正在回答
2回答
1、根据作业要求,限定作者、书名均为只读属性:也就说这两个属性只封装getter方法,在带参构造方法中通过this.name=name完成属性的赋值。
即:将作业和书名的setter方法去掉,带参构造方法中改为:
public Book(String name,String author,String press,float price) {
this.name=name;
this.author=author;
this.setPress(press);
this.setPrice(price);;
}2、优化建议:同学可以使用带参构造方法完成对象的初始化,使得代码看起来更加简洁。
即 Book bk1=new Book("红楼梦","曹雪芹","人民文学出版社",10);
祝学习愉快!
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星