美文网首页
24-案例分析六(Book)

24-案例分析六(Book)

作者: c88bc9f9d088 | 来源:发表于2020-11-01 14:27 被阅读0次

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

class Book{
    private int bid;
    private String title;
    private double price;
    private static int count = 0;
    
    public Book() {} //无参构造方法 必须有
    public Book(String title,double price) {
        this.bid = count ++; //先赋值再进行count的自增
        this.title = title;
        this.price = price;
    }
    public static int getCount() {
        return count;
    }
    
    public String getInfo() {
        return "图书编号:" + this.bid + "、名称:"+ this.title+"、价格:"+this.price;
    }
    
    public void setbid(int bid) {
        this.bid = bid;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    public double getBid() {
        return this.bid;
    }
    public String getTitle() {
        return this.title;
    }
    public double getPrice() {
        return this.price;
    }
}
public class JavaDemo{
    public static void main(String args[]){
        Book b1 = new Book("Java",89.2);
        Book b2 = new Book("Oracle",79.8);
        System.out.println(b1.getInfo());
        System.out.println(b2.getInfo());
        System.out.println("图书总册数:"+Book.getCount());
        
    }   
}

    在面向对象最基础的开发里面,简单Java类是解决先期设计最好的方案。

相关文章

网友评论

      本文标题:24-案例分析六(Book)

      本文链接:https://www.haomeiwen.com/subject/ncoyvktx.html