1-7 编程练习 Book类的问题
来源:1-7 编程练习
慕容2892559
2020-02-27 10:26:40
public class Book {
//私有属性:书名、作者、出版社、价格
private String book,author,press;
private double price;
//通过构造方法实现属性赋值
public Book(String book,String author,String press,double price){
this.book=book;
this.author=author;
setPress(press);
setPrice(price);
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getBook(){
return this.book;
}
public String getAuthor(){
return this.author;
}
public void setPress(String press){
this.press=press;
}
public String getPress(){
return this.press;
}
public void setPrice(double price){
if(price<10){
System.out.println("图书价格最低10元");
this.price=10.0;
}else{
this.price=price;
}
}
public double getPrice(){
return this.price;
}
//信息介绍方法,描述图书所有信息
public void message(){
System.out.println("书名:"+this.book);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.press);
System.out.println("价格:"+this.price+"元");
}
}效果已经实现了,问题是我有一些地方不太明白。
1. 限定作者、书名为只读属性,是不是说作者和书名只有get方法?
2. 构造函数中要求对属性名赋值,那是不是只能像我的代码这样写(我是按照本题目实现效果做的)?
1回答
同学你好,
1、限定作者、书名为只读属性,是不是说作者和书名只有get方法?
是的,同学理解是正确的。
2、构造函数中要求对属性名赋值,同学的构造方法定义正确,赋值体现在测试类中。如下所示:

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题