Java does not allow dynamic variables. Instead, you should use object-oriented design methods.
In this case, you must define an abstract class Stock with common methods and members and extend this class to types: Book , Bookmark > etc. See below for an example.
The benefits of using an abstract class for stocks (which none of the other answers have yet been shown) is that the "Stock" element cannot exist by itself. It makes no sense to have 5 stocks on a sellerโs shelf just as it makes sense to have 5 books on a sellerโ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. }
Please note that in order to determine what type of object you deal with later, if you absolutely need to, you will use checks such as:
if (myStock instanceof Book) { ... }
source share