Is it possible to create different objects dynamically from a superset object. For example:
SuperSet Object:
class Z { // some attributes }
class A {
String a, m, f, c;
int x,y,z;
Z z;
}
Child Objects required to be created dynamically from A:
class B {
String b; // mapped with value of a of A
String d; // mapped with value of m of A
int a; // mapped with value of x of A
int b; // mapped with value of y of A
}
class C {
String y; // mapped with value of f of A
String z; // mapped with value of c of A
int z; // mapped with value of z of A
Z b; // mapped with value of z of A
}
I would like to create such different child classes having different members which are subset of parent class A.
I know the normal way of creating skeleton class for each child object wanted and then map with values from superset object. Instead is there a way to map different parent class member values to child objects members dynamically.
Advertisement
Answer
I am assuming the correspondence stated above is fixed. I mean, field b of Class B
will always take the value of A. You can achieve this with a constructor designed accordingly. The code follows,
class B {
String b; // mapped with value of a of A
String d; // mapped with value of m of A
int a; // mapped with value of x of A
int b; // mapped with value of y of A
public B (A a) {
this.b = A.a // A.getA() alternatively
this.d = A.m // A.getM() alternatively
this.a = A.x // A.getX() alternatively
this.b = A.y // A.getY() alternatively
}
}
Now, what happens above is that in the constructor of B
you provide A and map the intended values of A onto the intended fields of B. Note, this can be done regardless of the fact that B is or is not a child of A. So, assuming you need to have B as a child of A you can do as follows:
class B extends A{
String b; // mapped with value of a of A
String d; // mapped with value of m of A
int a; // mapped with value of x of A
int b; // mapped with value of y of A
public B (A a) {
this.b = A.a // A.getA() alternatively
this.d = A.m // A.getM() alternatively
this.a = A.x // A.getX() alternatively
this.b = A.y // A.getY() alternatively
}
}
Cheers,
D