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

45 篇文章 1 订阅
23 篇文章 3 订阅

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

四、参考代码:


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); // 创建对象的同时给属性赋值
        b1.information(); // 对象调用方法
        System.out.println("===================");
        Book b2 = new Book("绝代双骄", "古龙", "中国长安出版社", 55.5);
        b2.information();
    }

}


五、效果截图:
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值