封装 编程练习1-7

封装 编程练习1-7

public class BookTest {

     // 测试方法
	 public static void main(String[] args) {
      //实例化对象,调用相关方法实现运行效果
      Book one=new Book("红楼梦", "曹雪芹","人民文学出版社",9.0);
      Book two=new Book("小李飞刀", "古龙","中国长安出版社",55.5);
      //Book one=new Book(9.0);
    //   one.setName("红楼梦");
    //   one.setAuthor("曹雪芹");
    //   one.setPublication("人民文学出版社");
    //   one.setPrice(10.0);
      one.information();
      System.out.println("================================");
      two.information();
   
     }
}
public class Book {
  //私有属性:书名、作者、出版社、价格
  private String name,author,publication;
  private double price;
  //通过构造方法实现属性赋值
  public Book(String name, String author, String publication, double price){
      
      this.name=name;
      this.author=author;
      this.publication=publication;
      this.price=price;
    //   this.setName(name);  //?????
    //   this.setAuthor(author);
       //this.setPublication(publication);
       //this.setPrice(price);
    
  }
  
  // set/get 设定
  //限定作者为只读属性
  public String getName(){
      return name;
  }
  //限定书名均为只读属性
  public String getAuthor(){
      return author;
  }
  ////////////////////////////
  public String getPublication(){
      return publication;
  }
  public void setPublication(){
      this.publication=publication;
  }
  public double getPrice(){
      return price;
  }
  public void setPrice(){
      if(price<10.0){
          System.out.println("图书价格最低10元");
          price=10.0;
      }
      else{
          this.price=price;
      }
  }

    /*通过公有的get/set方法实现属性的访问,其中:
    1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
    2、限定作者、书名均为只读属性
    */
    
  //信息介绍方法,描述图书所有信息
  public void information(){
      System.out.println("书名:"+this.name);
      System.out.println("作者:"+this.author);
      System.out.println("出版社:"+this.publication);
      System.out.println("价格:"+this.getPrice()+"元");
  }


}

http://img1.sycdn.imooc.com//climg/5c323596000143db03370281.jpg

请问为何我写的set和get不能对非目标价格作出限定,谢谢。

正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学的setter方法,书写格式是错误的;

setter方法中是有方法参数的,例如

public void setPublication(String publication) {

this.publication = publication;

}

建议同学根据上面的建议对所有的setter方法进行修改;

在Book类的带参构造方法中,应该使用this.setPrice(price)对价格进行赋值。

另外,在Eclipse生成Getter和Setter方法时,可以使用编辑器自动生成,生成方式:

在Book.java内右键空白区域——选择Source——选择Generate Getters and Setters...

选择需要生成getter和setter方法的属性,Eclipse就会自动生成了,这样就避免了书写错误哟。

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师