如何使用现有的基类对象构造派生类

问题描述 投票:0回答:2

我需要从现有的Fruit对象构造类,例如Apple或Strawberry。

这是我的Fruit类:

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;
    }
}

这是我的苹果和草莓课:

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));

[当我发现它是哪种水果时,我需要用苹果或草莓(与超级对象具有相同的水果对象)替换该水果对象。当然不停止某个线程。

这就是我的解决方法:

fruits.replace(17, new Strawberry(fruits.get(17)));
fruits.replace(24, new Apple(fruits.get(24)));
fruits.replace(95, new Strawberry(fruits.get(95)));

我的问题是:

可以简化吗?我的解决方案正确吗?

还有一个问题,如果我在草莓中有经常从其他线程调用的函数,如何确保在哈希映射值替换期间没有问题?

非常感谢您的帮助:)

java multithreading subclass superclass
2个回答
0
投票

对于并发修改,请使用Collections.synchronizedMap或ConcurrentHashMap。

关于简化,您可以指定要简化的内容吗?不必写构造函数吗?


0
投票

回答问题“ 可以简化吗?我的解决方案正确吗?

是。您不必在这里完全执行replace,因为放置在地图中的对象的类型为Fruit,只是在需要对其进行操作时将其强制转换。

如果您想更具体一些,也可以像obj instanceof Fruit一样进行检查。

此外,您的代码看起来也不安全,因为也提到了@ miszcz2137,并行修改迫在眉睫。

© www.soinside.com 2019 - 2024. All rights reserved.