5-9 声明一个图书类

5-9 声明一个图书类,其数据成员为书名、编号(利用静态变量实现自动编号)、书价,并拥有静态数据成员册数、记录图书的册数,在构造方法中利用此静态变量为对象的编号赋值,在主方法中定义对象数组,并求出总册数。

class Book{
    private String name;
    private int id;
    private float price;
    private static int num=3;
    private static int count=0;

    public Book(){           //无参构造函数
        count++;
        this.id=count;
    }

    public Book(String name,float price){      //双参构造函数
        this.name=name;
        this.price=price;
        this.id=(++count);
    }
    public int getId(){       //获取编号
        return this.id;
    }
    public int getNum(){      //获取数量
        return this.num;
    }
    public void print(){             //显示编号、书名、价格
        System.out.println("编号"+getId()+"  书名"+this.name+"  价格"+price);
    }
}

public class fiveDemo09{
    public static void main(String args[]){
        Book book[]=new Book[3];            //创建对象数组
        book[0]=new Book("数学",11.1f);
        book[1]=new Book("语文",22.2f);
        book[2]=new Book("英语",33.3f);
        for(int i=0;i<book.length;i++){
            book[i].print();
        }
        System.out.println("总册数为 "+((new Book().getId()-1)*book[2].getNum()));    //输出总册数
    }
}
  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值