以面向对象的思想,编写自定义类描述图书信息。设定属性包括:书名,作者,出版社名,价格;设置属性的私有访问权限,通过公有的get,set方法实现对属性的访问

时间:2025-03-10 16:43:06
public class Book { // 设置属性的私有访问权限 private String name; private String author; private String publisher; private double price; // 通过公有的get,set方法实现对属性的访问 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public double getPrice() { return price; } public void setPrice(double price) { if (price > 10) { this.price = price; }else{ System.out.println("价格无效,必须大于10"); } } // 无参构造方法 public Book() { } // 有参构造方法 实现属性赋值 public Book(String name, String author, String publisher, double price) { // 有四个参构造方法 this.name = name; this.author = author; this.publisher = publisher; this.setPrice(price); } public void information() { // 展示信息的方法 System.out.println("书名:" + this.getName()); System.out.println("作者:" + this.getAuthor()); System.out.println("出版社:" + publisher); System.out.println("价格:" + price + "元"); } } public class TestBook { public static void main(String[] args) { Book b1 = new Book("鹿鼎记", "金庸", "人民文学出版社", 120.0); // 创建对象的同时给属性赋值 (); // 对象调用方法 System.out.println("==================="); Book b2 = new Book("绝代双骄", "古龙", "中国长安出版社", 55.5); (); } }