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;
}
You might want to consider using polymorphism.
public class Stock {
int stockPrice;
int stockQuantity;
int stockType;
}
public class Book extends Stock{
int pages;
boolean hardcover;
}
public class Bookmark extends Stock {
String pattern;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With