Java類對象id號的自動生成,以Book爲例,bookId自動生成案例

1:創建Book類

package com.dareway.test4;
public class Book {
private int no;
private String name;
private double price;
private static int num = 3;
private static int count = 0;
public Book(){
count++;
this.no = count;
}

public Book(String name, double price) {
super();
this.name = name;
this.price = price;
this.num = num;
}
public int getNo() {
return no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static int getNum() {
return num;
}
public static void setNum(int num) {
Book.num = num;
}
}

2:創建Test類

package com.dareway.test4;


public class Test {


public static void main(String[] args) {
Book [] book = new Book[4];
book[0] = new Book("Java",33.5);
book[1] = new Book("Oracle",52.5);
book[2] = new Book("Html",34.5);
book[3] = new Book("Mysql",53.5);
for(int i = 0;i<book.length;i++){
System.out.println("編號:"+new Book().getNo()+" 名稱:"+book[i].getName()+" 價格:"+book[i].getPrice()+" 數量:"+book[i].getNum());
}
System.out.println("圖書總數量:"+(new Book().getNo()+1)*book[1].getNum());
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章