I have a Parent class and 26 child classes and want to save state of the instance of one of this class.
The parent class:
public class ParentClass {
protected String name;
protected String type;
public ParentClass(String name) {
this.name = name;
this.type = "Parent";
}
public ParentClass(ParentClass src){
this.name = src.name;
this.type = src.type;
}
}
The first child class, which contain additional fields. public class ChildClassA extends ParentClass { protected String value;
public ChildClassA(String name, String value) {
super(name);
this.value = value;
this.type = "A";
}
public ChildClassA(ChildClassA src) {
super(src);
this.value = src.value;
}
}
The last child class which contain another fields. public class ChildClassZ extends ParentClass { protected int size;
public ChildClassZ(String name, int size) {
super(name);
this.size = size;
this.type = "Z";
}
public ChildClassZ(ChildClassZ src) {
super(src);
this.size = src.size;
}
}
To save state of unknown class I use a constructor in child class with parameter of this class, define class type and initiate by case structure.
Is it possible to avoid using case or if-then-else structure to make code more readable? May be reflection.
public static void main(String[] args) {
ParentClass a = new ChildClassA("classA", "585");
ParentClass z = new ChildClassZ("classB", 1024);
a.name = "changedName";
ParentClass originalState2 = null;
System.out.println("Test Test");
switch (z.type) {
case "A":
originalState2 = new ChildClassA((ChildClassA)z);
case "Z":
originalState2 = new ChildClassZ((ChildClassZ)z);
}
System.out.println("The original name is " + originalState2.name + " and the type is " + originalState2.type +
", the value is " + ((ChildClassZ)originalState2).size);
}
Aucun commentaire:
Enregistrer un commentaire