正在回答 回答被采纳积分+1
3回答
oreooooo
2017-08-19 13:18:17
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 65 66 67 68 69 70 | class Book{ //私有属性:书名、作者、出版社、价格 private String bookName; private String author; private String press; private double price; //通过构造方法实现属性赋值 书名和作者 public Book(String bookName,String aurhor) { this .bookName=bookName; this .author=aurhor; } /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public double getPrice() { return price; } public void setPrice( double price) { if (price< 10 ) { System.out.println( "您输入的价格无效。" ); this .price= 10.0 ; } else { this .price = price; } } //书名只设置为只读 public String getBookName() { return this .bookName; } //作者只设置为只读 public String getAuthor() { return this .author; } public String getPress() { return this .press; } public void setPress(String press) { this .press=press; } public void infoIntroduction() { System.out.println( "书名:" +getBookName()); System.out.println( "作者:" +getAuthor()); System.out.println( "出版社:" +getPress()); System.out.println( "价格:" +getPrice()+ "元" ); } } public class BookTest { public static void main(String[] args) { Book bookCao= new Book( "红楼梦" , "曹雪芹" ); bookCao.setPress( "人民出版社" ); bookCao.setPrice( 10.0 ); bookCao.infoIntroduction(); System.out.println( "====================" ); Book bookGu= new Book( "小李飞刀" , "古龙" ); bookGu.setPress( "中国长安出版社" ); bookGu.setPrice( 55.5 ); bookGu.infoIntroduction(); } } |
这是助教老师的方法,用构造器传入作者和书名。但我感觉没用用到封装性,外界还是可以通过构造器随便的更改书名和作者。
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧