Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Class when its attributes are dynamic & variable in Java, C++ or any Object-Oriented Language?

Tags:

java

c++

oop

vb.net

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?

like image 933
Tum Avatar asked Oct 03 '22 06:10

Tum


1 Answers

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.

like image 183
Reed Copsey Avatar answered Oct 07 '22 19:10

Reed Copsey