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