Java自定义类实现图书信息设置。

package test;


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元");
            this.price = 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 + "元");
    }

}

_____________________________________________________________________________

package test;

public class TestBook {
    public static void main(String[] args) {
        Book b1 = new Book("红楼梦", "曹雪芹", "人民文学出版社", 10.0); // 创建对象的同时给属性赋值
        b1.information(); // 对象调用方法
        System.out.println("===================");
        Book b2 = new Book("小李飞刀", "古龙", "中国长安出版社", 55.5);
        b2.information();
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四维空间中的未知点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值