java封装练习
/*** 以面向对象的思想,编写自定义类描述图书信息。设定属性包括:书名、作者、出版社名、价格* 方法包括:信息介绍** 要求:* 1、设置属性的私有访问权限,通过公有的get、set方法实现对属性的访问* 2、限定价格必须大于10,如果无效进行提示* 3、设计构造方法实现对属性赋值* 4、信息介绍方法描述图书所有信息* 5、编写测试类,测试对图书类的对象及相关方法(测试数据信息自定)*/
public class Book {private String bookName;private String author;private String publisher;private double price;public Book(){}public Book(String bookName,String author,String publisher,double price){this.bookName = bookName;this.author = author;this.publisher = publisher;this.price = price;}public void setBookName(String bookName){this.bookName = bookName;}public String getBookName(){return this.bookName;}public void setAuthor(String author){this.author = author;}public String getAuthor(){return author;}public void setPublisher(String publisher) {this.publisher = publisher;}public String getPublisher() {return publisher;}public void setPrice(double price){if (price<10){this.price = 10;System.out.println("价格必须大于10元,默认10元");}else {this.price = price;}}public double getPrice(){return this.price;}public void show(){System.out.println("bookName:"+bookName+"\t"+"author:"+author+"\t"+"publisher:"+publisher+"\t"+"price:"+price);}public static void main(String[] args) {Book book1 = new Book();book1.setBookName("西游记");book1.setAuthor("吴承恩");book1.setPublisher("清华大学出版社");book1.setPrice(6);book1.show();Book book2 = new Book("红楼梦","曹雪芹","清华大学出版社",30);book2.show();}}
执行代码如下: