1、编程题目
编写自定义类实现图书信息设置,运行参考效果如下所示:
图书价格最低10元
书名:红楼梦
作者:曹雪芹
出版社:人民文学出版社
价格:20.0元
====================
书名:小李飞刀
作者:古龙
出版社:长安出版社
价格:55.5元
提示:
1)用构造函数实现对属性赋值;
2)设置私有属性,get/set方法实现对属性的访问。
2、编程内容
public class Book {
//私有属性:书名、作者、出版社、价格
private String bookName;
private String writer;
private String press;
private float price;
//通过构造方法实现属性赋值
public Book(String bookName,String writer,String press,float price){
this.bookName=bookName;
this.writer=writer;
this.setPress(press);
this.setPrice(price);
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getBookName(){
return bookName;
}
public String getWriter(){
return writer;
}
public void setPress(String press){
this.press=press;
}
public String getPress(){
return press;
}
public void setPrice(float price){
if(price<=10){
System.out.println("图书价格最低10元");
this.price=10f;
}else{
this.price=price;
}
}
public float getPrice(){
return price;
}
//信息介绍方法,描述图书所有信息
public void info(){
System.out.println("书名:"+this.getBookName());
System.out.println("作者:"+this.getWriter());
System.out.println("出版社:"+this.getPress());
System.out.println("价格:"+this.getPrice()+"元");
}
}
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book one,two;
one=new Book("红楼梦","曹雪芹","人民文学出版社",20.0f);
two=new Book("小李飞刀","古龙","长安出版社",55.5f);
one.info();
System.out.println("====================");
two.info();
}
}