java封装题目3

3.以面向对象的思想,编写自定义类描述图书信息。设定属性包括:书名,作者,出 版社名,价格;方法包括:信息介绍 show()
要求:
1)设置属性的私有访问权限,通过公有的 get,set 方法实现对属性的访问
2)限定价格必须大于 10,如果无效进行提示
3)限定作者,书名为只读属性
4)设计构造方法实现对属性赋值
5)信息介绍方法描述图书所有信息
6)编写测试类,测试图书类的对象及相关方法(测试数据信息自定) 运行效果图:

编写一个Book类

class Book{
    private String name;
    private String actor;
    private String publisher;
    private double price;

    public Book(){ //无参构造方法

    }
    public Book(String name,String actor,String publisher,double price){ //有参构造方法
        this.name=name;
        this.actor=actor;
        this.publisher=publisher;
        this.price=price;

    }

    public String getName() {
        return name;
    }



    public String getActor() {
        return actor;
    }



    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(int price) { //对价格进行判断,价格必须大于10
        if(price>10){
            this.price=price;
        }else {
            this.price=0.0;
            System.out.println("输入的价格不合理,已改为默认值");
        }
    }
    public void show(){  //进行信息展示
        System.out.println("书名:" + name +"\n" +"作者:" + actor +"\n"+ "出版社:" + publisher +"\n" +"价格:" + price+"元");
    }
}

编写测试类

public class Test3 {
    public static void main(String[] args) {
        Book b1 = new Book("鹿鼎记","金庸","人民文学出版社",120.0);
        b1.show();
        System.out.println("==========================");
        Book b2 = new Book("绝代双骄","古龙","中国长安出版社",55.5);
        b2.show();
    }
}
posted @ 2024-09-24 20:24  你的镁偷走了我的锌  阅读(19)  评论(0)    收藏  举报