我想通过选择用户来更改变量的名称.我知道它可以由Mab来完成(不是很吸引人),但我认为它也可以通过多态来完成,至少可以模拟它.很难解释,因此下面的代码可以更好地说明它.谢谢!
public class Main {
public static void main(String[] args) {
GenericObject o;
o = new Object1(10, 10);
o.wh();
System.out.println(o.w); // Output: 3 (ok)
System.out.println(o.h); // Output: 10 (ok)
o = new Object2(10, 10);
o.wh();
System.out.println(o.w); // Output: 7 (ok)
System.out.println(o.h); // Output: 4 (ok)
String inputFromUser = "1";
o = new Object + inputFromUser + (10, 10); /*I know that is an absurd, just to illustrate...
if polymorphism can solve this problem, I thik it's the best option. So how use it here?
I don't wanna use ifs or switchs, I will use more than 300 classes*/
o.wh();
System.out.println(o.w); // Output: 3 (that's what I wanna obtain)
System.out.println(o.h); // Output: 10 (that's what I wanna obtain)
}
}
abstract class GenericObject {
int w, h, x, y;
GenericObject (int x, int y) {
this.x = x;
this.y = y;
}
public abstract void wh();
}
class Object1 extends GenericObject{
Object1 (int x, int y) {
super(x, y);
}
@Override
public void wh () {
w = 3;
h = 10;
}
}
class Object2 extends GenericObject{
Object2 (int x, int y) {
super(x, y);
}
@Override
public void wh () {
w = 7;
h = 4;
}
}
解决方法:
希望下面的代码对您有所帮助.
HashMap<String, GenericObject > allTypes = new HashMap<>();
allTypes.put("1", new Object1(10, 10));
allTypes.put("2", new Object2(10, 10));
String inputFromUser = "1";
GenericObject o = allTypes.get(inputFromUser);
o.wh();
System.out.println(o.w); // Output: 3
System.out.println(o.h); // Output: 10