Ok, in Object-Oriented Language (OOL), when creating a Class we often know in advance all its attributes. Ex, Item class should have a fixed attributes (Color, model, brand, price). So we just:
public Class Item{
private String color;
private String model;
//etc more attribute here
//& set & get method for all attributes
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
But what if all the attributes are dynamic? Ex, in 1 company, their item attributes could be color, brand, but in other company, they don't have color & brand attributes but have width, height, size...
How to create a Class that accepts dynamic attributes in Java, C++ or in any OOL?
How to create a Class that accepts dynamic attributes in Java, C++ or in any OOL?
It really depends on how you want to use this. In many cases, you could rework your class to contain some type of dynamically growing collection, such as a std::map
in C++ or a Map
(or Dictionary
) in Java.
This allows you to create and add arbitrary data per instance with a key chosen at runtime.
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