Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have dynamic variables for class members?

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;
}
like image 463
Arvanem Avatar asked Dec 08 '22 03:12

Arvanem


1 Answers

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;
}
like image 92
Jon Quarfoth Avatar answered Dec 15 '22 17:12

Jon Quarfoth