gpt4 book ai didi

java - java变量的多态或改名

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:07:52 25 4
gpt4 key购买 nike

我想根据用户的选择更改变量的名称。我知道它可以通过 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

关于java - java变量的多态或改名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33295073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com