怎么修改才能达成需要的效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | public class Book { //私有属性:书名、作者、出版社、价格 private String title; private String author; private String press; private double price; //通过构造方法实现属性赋值 public Book(String title,String author,String press, double price){ this .title=title; this .author=author; this .press=press; this .price=price; } /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public String gettitle(){ return title; } public String getauthor(){ return author; } public String getpress(){ return press; } public void setpress(){ this .press=press; } public double getprice(){ return price; } public void setprice( double price){ if (price> 10 ){ this .price=price; } else { System.out.println( "图书价格必须大于10" ); this .price= 10 ; } } //信息介绍方法,描述图书所有信息 public void show(){ System.out.println( "书名:" +title); System.out.println( "作者:" +author); System.out.println( "出版社:" +press); System.out.println( "价格:" +price+ "元" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public class BookTest { // 测试方法 public static void main(String[] args) { //实例化对象,调用相关方法实现运行效果 Book one= new Book( "红楼梦" , "曹雪芹" , "人民文学出版社" , 8 ); Book two= new Book( "小李飞刀" , "古龙" , "中国长安出版社" , 55.5 ); one.show(); System.out.println( "===================================" ); two.show(); } } |
10
收起
正在回答
1回答
同学你好,同学的代码中存在以下问题:
1.由于同学的Book类的有参构造中使用的this属性形式,没有使用到set方法,所以无法对price属性进行限制。建议构造方法中使用set方法进行赋值。
2.set和get方法的命名不规范,应当在第二个单词开始,每个单词的首字母大写,例如gettitle应当为getTitle。
3.setpress方法应当有参数,用于对属性进行赋值。
4.title和author属性没有对应的set方法。
修改后的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | public class Book { // 私有属性:书名、作者、出版社、价格 private String title; private String author; private String press; private double price; // 通过构造方法实现属性赋值 public Book(String title, String author, String press, double price) { this .setTitile(title); this .setAuthor(author); this .setPress(press); this .setPrice(price); } /* * 通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public String getTitle() { return title; } public void setTitile(String title) { this .title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this .author = author; } public String getPress() { return press; } public void setPress(String press) { this .press = press; } public double getPrice() { return price; } public void setPrice( double price) { if (price > 10 ) { this .price = price; } else { System.out.println( "图书价格必须大于10" ); this .price = 10 ; } } // 信息介绍方法,描述图书所有信息 public void show() { System.out.println( "书名:" + title); System.out.println( "作者:" + author); System.out.println( "出版社:" + press); System.out.println( "价格:" + price + "元" ); } } |
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧