我需要从现有的 Fruit 对象构造类,例如 Apple 或 Strawberry。
这是我的水果课:
public class Fruit {
int somevariable;
Thread somethread;
public Fruit(int somevariable) {
this.somevariable = somevariable;
this.somethread = new Thread() {
public void run() { /* Something here */ }
}
this.somethread.start();
}
public Fruit(Fruit fruit) {
this.somevariable = fruit.somevariable;
this.somethread = fruit.somethread;
}
}
这是我的苹果和草莓类(class):
public class Apple extends Fruit {
public Apple(Fruit fruit) {
super(fruit);
}
}
public class Strawberry extends Fruit {
public Strawberry(Fruit fruit) {
super(fruit);
}
}
我有这样的 HashMap:
HashMap<Integer, Fruit> fruits = new HashMap<>();
首先,我添加这样的水果: (我只知道这是目前的水果。我不能立即添加苹果或草莓。)
fruits.put(17, new Fruit(4));
fruits.put(24, new Fruit(8));
fruits.put(95, new Fruit(12));
当我找出它是什么类型的水果时,我需要用苹果或草莓替换水果对象(与 super 对象具有相同的水果对象)。当然,无需停止某个线程。
这就是我解决这个问题的方法:
fruits.replace(17, new Strawberry(fruits.get(17)));
fruits.replace(24, new Apple(fruits.get(24)));
fruits.replace(95, new Strawberry(fruits.get(95)));
我的问题是:
这可以变得更容易吗?我的解决方案正确吗?
还有一个问题,如果我的草莓中有经常被其他线程调用的函数,如何确保在 hashmap 值替换期间没有问题?
非常感谢您的帮助:)
最佳答案
优先选择组合而不是继承。通常不会对具体类进行子类化(Object
除外,尽管目前这种具体类已被“弃用”)太棒了。
Fruit
应该有一个 FruitType
(或更好的名称)。根据需要进行委托(delegate)。
另请注意,在原始代码中,Runnable
(编辑: Thread
没有被覆盖run
) 将在原始 Fruit
实例的上下文中创建。此外,线程最初会看到一个不能保证完全初始化的 Fruit
。
关于java - 如何使用现有基类对象构造派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60479728/