I am wondering whether it is possible to make dynamic variables in Java. In other words, variables that change depending on my instructions.
EDIT Rephrasing my question, I mean variables for a class that change type depending on a given variable (stockType, for those who read on).
FYI, I am making a trading program. A given merchant will have an array of items for sale for various prices.
The dynamism I am calling for comes in because each category of items for sale has its own properties. For example, a book item has two properties: int pages, and boolean hardCover. In contrast, a bookmark item has one property, String pattern.
Here are skeleton snippets of code so you can see what I am trying to do:
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
}
and
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 does not allow dynamic variables. Instead, you should apply object oriented design techniques.
In this case, you should define an abstract class Stock with common methods and members and extend that class for the types: Book, Bookmark, etc. See below for an example.
The advantages to using an abstract class for Stock (which none of the other answers have yet shown) is that a “Stock” item can’t really exist on its own. It doesn’t make sense to have 5 Stocks on a Merchant’s shelf in the same way that it makes sense to have 5 Books on a Merchant’s shelf.
Note that in order to determine which type of object you are dealing with later, if you absolutely have to, you’ll use checks like: