正在回答 回答被采纳积分+1
3回答
oreooooo
2017-08-19 13:18:17
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积分~
来为老师/同学的回答评分吧
0 星