4

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;
}
3
  • Please rephrase the question. Variables are by definition "dynamic", and can be changed by instructions (you have to mark them 'final' if you want to avoid this in Java). I think you are looking for "Objects" in OO parlance.
    – tucuxi
    Apr 7, 2010 at 23:14
  • Thanks, you're right. I have rephrased based on the helpful title edit by Pyrolistical.
    – Arvanem
    Apr 7, 2010 at 23:39
  • This is actually technically possible using reflection and some sort of class editing library, but definitely not recommended... Apr 7, 2010 at 23:43

6 Answers 6

5

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;
}
5

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();
}
2
  • 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. Apr 7, 2010 at 23:15
  • 1
    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. Apr 7, 2010 at 23:20
4

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) { ... }
2
  • 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
    Apr 7, 2010 at 23:47
  • Arvanem: since Book and Bookmark extend Stock, they'll happily go into a Stock[] without any complaints. :)
    – JavadocMD
    Apr 8, 2010 at 0:15
1

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

5
  • Thank you for the tip about List. I will swap my Arrays to List asap.
    – Arvanem
    Apr 7, 2010 at 23:14
  • "... 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
    Apr 7, 2010 at 23:23
  • 1
    @Stephen hush! There will be no talk of implementations details! I live in a world of abstraction therefore your points are moot! =) Apr 7, 2010 at 23:29
  • By the way, this trading program will be implemented one way or another IRL. Not an abstract thing at all. :)
    – Arvanem
    Apr 7, 2010 at 23:43
  • this is not a mere implementation detail. It is a fundamental point about the design of the Java language.
    – Stephen C
    Apr 8, 2010 at 0:04
0

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.