views:

298

answers:

6

Hi folks,

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;
}
A: 

I'm not sure what you want exactly, but it sounds like the State design-pattern might be something for you to check out.

Frederik Wordenskjold
A: 

You can use a factory design pattern here. The reason being, based on the stockType you want an object that is specific/dynamic, which a factory would provide for you.

Bragboy
+1  A: 

NO and for good reason.

Anyways to do what you want instead of having a stockType, Subclass Stock into the different types you want.

Give us examples of what you want to do with the dynamic variables and we can show you how.

Also don't use arrays. They are fixed length and only really there to be C++ like. Use List instead.

Replace Stock[] itemsForSale = new Stock[10]; with List<Stock> itemsForSale = new ArrayList<Stock>(); and read up about List

Pyrolistical
Thank you for the tip about List. I will swap my Arrays to List asap.
Arvanem
*"... and only really there to be C++ like"*. Nonsense. Arrays are there because they are *essential* for implementing a whole lot of classes that cannot be implemented efficiently using lists. For example, String, StringBuilder, the stream APIs, ... ArrayList, and HashMap!
Stephen C
@Stephen hush! There will be no talk of implementations details! I live in a world of abstraction therefore your points are moot! =)
Pyrolistical
By the way, this trading program will be implemented one way or another IRL. Not an abstract thing at all. :)
Arvanem
@Pyrolistical - this is not a mere implementation detail. It is a fundamental point about the design of the Java language.
Stephen C
+5  A: 

Subclass your Stock for each stock type:

public class Stock {
    private int price;
    private int quantity;
}

public class StockBook extends Stock {
    private int pages;
    private boolean hardCover;
}

public class StockBookmark extends Stock {
    private String pattern;
}

Or use Map for the different types of attributes:

public class Stock {
    private int price;
    private int quantity;
    private String classification; // e.g. book and bookmark
    private Map properties = new HashMap();
}
Lie Ryan
Don't use HashMap as part of your type in Stock. Use Map. HashMap is an implementation and should not be referenced to unless you really mean it.
Pyrolistical
Right, thanks for spotting that. Edited.
Lie Ryan
The Stock type should probably be an enumeration to catch errors at compile time. Also `stockPrice` is a bit redundant, as it is part of the stock class.
Dave Jarvis
+5  A: 

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;
}
Jon Quarfoth
+2  A: 

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.

public abstract class Stock {
    private int stockPrice;
    private int stockQuantity;

    // Implement getters and setters for stockPrice and stockQuantity.
}

public class Book extends Stock {
    // Since I'm extending Stock, I don't have to redefine price or quantity
    private int pages;
    private boolean hardCover;

    // Implement getters and setters for pages and hardCover.
}

public class Bookmark extends Stock {
    private String pattern;

    // Implement getters and setters for pattern.
}

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:

if (myStock instanceof Book) { ... }
JavadocMD
This is an elegant solution, but I am wondering how I would handle collecting all the book and bookmark items into the array or list of Stock[] itemsforSale in the Merchants class?
Arvanem
Arvanem: since Book and Bookmark extend Stock, they'll happily go into a Stock[] without any complaints. :)
JavadocMD