关于编程问题 是否正确
来源:1-3 封装的代码实现(下)
慕雪5389121
2019-03-30 08:55:39
public class Book {
//私有属性:书名、作者、出版社、价格
private String bookName;
private String author;
private String publisher;
private double price;
//通过构造方法实现属性赋值
public Book(String bookName1,String author1, String publisher1, double price1){
this.bookName=bookName1;
this.author=author1;
this.publisher=publisher1;
this.price=price1;
}
public String getBookName(){
return bookName;
}
public String getAuthor(){
return author;
}
public String getPublisher(){
return publisher;
}
public void setPublisher(String newPublisher){
this.publisher=newPublisher;
}
public double getPrice(){
return price;
}
public void setPrice(double newPrice){
this.price=newPrice;
if(newPrice>10){
price=newPrice;
}else{
System.out.println("无效,必须大于10");
price=10;
}
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
//信息介绍方法,描述图书所有信息
public void showInfo(){
System.out.println("书名:"+getBookName());
System.out.println("作者:"+getAuthor());
System.out.println("出版社:"+getPublisher());
System.out.println("价格:"+getPrice());
}
}
public class BookTest {
public static void main(String[] args) {
Book myObj1=new Book("红楼梦","曹雪芹","人民文学出版社",10.0);
myObj1.showInfo();
System.out.println("=================================================================");
Book myObj2=new Book("小李飞刀","古龙","中国长安出版社",55.5);
myObj2.showInfo();
}
}
1回答
好帮手慕珊
2019-03-31
你好!程序运行效果正确,但还有几个问题:
1、如下选中的语句,可以去掉,因为后面的if-else结构会对price进行赋值。
2、因为价格是有限制的,所以构造方法中的this.price=price1;的代码,可以改成用setPrice()方法完成,这样就可以对价格进行限制。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题