表类
public Table() {
height = 0.0;
weight = 0.0;
color = "unknown";
numberOfLegs = 4;
inventoryNumber = 1;
numberOfTables++;
}// no args contructor
public Table(double h, double w, String c, int n) {
height = h;
weight = w;
color = c;
numberOfLegs = n;
inventoryNumber = 2;
numberOfTables++;
}// constructor
亚军课
Table kitchenTable = new Table();
Table diningTable = new Table(5.5, 9.9, "brown", 8);
Table picnicTable = new Table(3.3, 4.4, "red", 6);
Table babyTable = new Table();
如何在不使其成为静态变量的情况下增加库存编号 例如,我的跑步者类具有2个没有args构造函数和System out println两者,但是它们都具有1。而我想要第一个打印出1和第二个打印出2
答案 0 :(得分:0)
您有两个选择
可变
将此方法添加到您的Table
类中
public void incrementInventory() {
this.inventoryNumber++;
}
用法
Table mutableTable = new Table();
mutableTable.incrementInventory();
不变(推荐)
将此添加到您的Table
类
// new constructor
public Table(double h, double w, String c, int n, int inventory, int tables) {
height = h;
weight = w;
color = c;
numberOfLegs = n;
inventoryNumber = inventory;
numberOfTables = tables;
}
public Table incrementInventory() {
// new Table with the same all variables and inventory + 1
return new Table(
this.height, this.weight , this.color , this.numberOfLegs ,
this.inventoryNumber + 1, this.numberOfTables
);
}
用法
Table inmutableStateOne = new Table();
Table inventoryPlusOne = inmutableStateOne.incrementInventory();
然后,inmutableStateOne
将保持您的初始状态,而inventoryPlusOne
不变,但使用inventory + 1