【发布时间】:2011-02-05 11:49:13
【问题描述】:
我想知道是否可以在 Java 中制作动态变量。换句话说,根据我的指示而改变的变量。
编辑 重新表述我的问题,我的意思是类的变量会根据给定的变量(stockType,对于那些继续阅读的人)改变类型。
仅供参考,我正在制作一个交易程序。给定的商家将有一系列以各种价格出售的商品。
我所呼吁的活力是因为每个待售商品类别都有自己的属性。例如,一本书有两个属性:int pages 和 boolean hardCover。相反,书签项有一个属性,字符串模式。
这是代码的骨架 sn-ps,因此您可以看到我要做什么:
public class Merchants extends /* certain parent class */ {
// only 10 items for sale to begin with
Stock[] itemsForSale = new Stock[10];
// Array holding Merchants
public static Merchants[] merchantsArray = new Merchants[maxArrayLength];
// method to fill array of stock goes here
}
和
public class Stock {
int stockPrice;
int stockQuantity;
String stockType; // e.g. book and bookmark
// Dynamic variables here, but they should only be invoked depending on stockType
int pages;
boolean hardCover;
String pattern;
}
【问题讨论】:
-
请重新表述问题。变量根据定义是“动态的”,并且可以通过指令进行更改(如果您想在 Java 中避免这种情况,则必须将它们标记为“最终”)。我认为您正在寻找 OO 用语中的“对象”。
-
谢谢,你是对的。我已根据 Pyrolistical 的有用标题编辑重新措辞。
-
这实际上技术上可以使用反射和某种类编辑库,但绝对不推荐......