封装 编程练习1-7
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book one=new Book("红楼梦", "曹雪芹","人民文学出版社",9.0);
Book two=new Book("小李飞刀", "古龙","中国长安出版社",55.5);
//Book one=new Book(9.0);
// one.setName("红楼梦");
// one.setAuthor("曹雪芹");
// one.setPublication("人民文学出版社");
// one.setPrice(10.0);
one.information();
System.out.println("================================");
two.information();
}
}public class Book {
//私有属性:书名、作者、出版社、价格
private String name,author,publication;
private double price;
//通过构造方法实现属性赋值
public Book(String name, String author, String publication, double price){
this.name=name;
this.author=author;
this.publication=publication;
this.price=price;
// this.setName(name); //?????
// this.setAuthor(author);
//this.setPublication(publication);
//this.setPrice(price);
}
// set/get 设定
//限定作者为只读属性
public String getName(){
return name;
}
//限定书名均为只读属性
public String getAuthor(){
return author;
}
////////////////////////////
public String getPublication(){
return publication;
}
public void setPublication(){
this.publication=publication;
}
public double getPrice(){
return price;
}
public void setPrice(){
if(price<10.0){
System.out.println("图书价格最低10元");
price=10.0;
}
else{
this.price=price;
}
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
//信息介绍方法,描述图书所有信息
public void information(){
System.out.println("书名:"+this.name);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.publication);
System.out.println("价格:"+this.getPrice()+"元");
}
}
请问为何我写的set和get不能对非目标价格作出限定,谢谢。
0
收起
正在回答
1回答
同学的setter方法,书写格式是错误的;
setter方法中是有方法参数的,例如
public void setPublication(String publication) {
this.publication = publication;
}
建议同学根据上面的建议对所有的setter方法进行修改;
在Book类的带参构造方法中,应该使用this.setPrice(price)对价格进行赋值。
另外,在Eclipse生成Getter和Setter方法时,可以使用编辑器自动生成,生成方式:
在Book.java内右键空白区域——选择Source——选择Generate Getters and Setters...
选择需要生成getter和setter方法的属性,Eclipse就会自动生成了,这样就避免了书写错误哟。
祝学习愉快!
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星