java书名作者出版社_Java 面向对象封装的代码练习

public class BookTest {

// 测试方法

public static void main(String[] args) {

//实例化对象,调用相关方法实现运行效果

Book bk = new Book("红楼梦","曹雪芹");

bk.setPress("人民文学出版社");

bk.setPrice(10);

bk.showInfo();

System.out.println("===============");

Book bk2 = new Book("小李飞刀","古龙");

bk2.setPress("中国长安出版社");

bk2.setPrice(55.5);

bk2.showInfo();

}

}

public class Book {

private String name,author,press;

private double price;

//通过构造方法实现属性赋值

public Book(){

}

public Book(String name,String author){

this.name = name;

this.author = author;

}

/*通过公有的get/set方法实现属性的访问,其中:

1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10

*/

public void setPress(String press){

this.press = press;

}

public void setPrice(double price){

if(price<=10){

this.price=10;

System.out.println("图书价格最低10元");

}

else

this.price = price;

}

public String getName(){

return name;

}

public String getAuthor(){

return author;

}

public String getPress(){

return press;

}

public double getPrice(){

return price;

}

//信息介绍方法,描述图书所有信息

public void showInfo(){

System.out.println("书名:"+this.name);

System.out.println("出版社:"+this.press);

System.out.println("价格:"+this.price+"元");

}

}

public class BookTest { // 测试方法 public static void main(String[] args) { //实例化对象,调用相关方法实现运行效果 Book bk = new Book("红楼梦","曹雪芹"); bk.setPress("人民文学出版社"); bk.setPrice(10); bk.showInfo(); System.out.println("==============="); Book bk2 = new Book("小李飞刀","古龙"); bk2.setPress("中国长安出版社"); bk2.setPrice(55.5); bk2.showInfo(); } } public class Book { private String name,author,press; private double price; //通过构造方法实现属性赋值 public Book(){ } public Book(String name,String author){ this.name = name; this.author = author; } /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 */ public void setPress(String press){ this.press = press; } public void setPrice(double price){ if(price<=10){ this.price=10; System.out.println("图书价格最低10元"); } else this.price = price; } public String getName(){ return name; } public String getAuthor(){ return author; } public String getPress(){ return press; } public double getPrice(){ return price; } //信息介绍方法,描述图书所有信息 public void showInfo(){ System.out.println("书名:"+this.name); System.out.println("出版社:"+this.press); System.out.println("价格:"+this.price+"元"); } }
经验分享 程序员 微信小程序 职场和发展