Instantiate an object from one of many possible classes?
in
Programming Questions
•
11 months ago
I have a class Object1 that has an object called obj2 as a property. Depending on the instantiation of Object1, obj2 might be an instance of Object3 or Object4, extensions of the Object5 class.
At the moment I'm doing it like this:
- Object1 {
- int type;
- Object5 obj2;
- Object1 (int typein) {
- type = typein;
- switch (type) {
- case 0:
- obj2 = new Object3();
- break;
- case 1:
- ob2 = new Object4();
- break;
- }
- }
- void put(){
- obj2.put();
- }
- }
- class Object5 {
- Object5(){
- }
- }
- class Object3 extends Object5 {
- int foo;
- Object3 () {
- foo = floor(random(10));
- }
- void put(){
- text(foo,10,10);
- }
- }
- class Object4 extends Object5 {
- float bar;
- Object4 () {
- bar = random(10);
- }
- void put(){
- text(round(bar),10,10);
- }
- }
However, it's not working. The code above doesn't work unless Object5 also has int foo or float bar, and a push method, and then what I get is an instantiation of Object5 followed by Object3 or Object4, and changes to obj.obj2.foo or obj.obj2.bar are reflected in the Object5 instantiation and not in obj2's put method.
I feel like I must just be drastically misunderstanding how to extend a class, how to implement an object that might be an instance of several different classes, or perhaps even how to accomplish this altogether.
How can I fix this, or what is a better way to do it?
Thanks in advance.
1