自我在构造函数中为对象分配对象

时间:2018-04-26 12:52:17

标签: java inheritance constructor variable-assignment

让我们说:

班级@Bean KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Event>> eventProcessorListenerContainerFactory() { Map<String, Object> propMap = new HashMap<String, Object>(); propMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer); propMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); propMap.put(ConsumerConfig.GROUP_ID_CONFIG, "EventProcessorConsumer"); DefaultKafkaConsumerFactory<String, Event> consuemrFactory = new DefaultKafkaConsumerFactory<String, Event>( propMap); consuemrFactory.setValueDeserializer(new AvroDeSerializer<Event>( Event.class)); ConcurrentKafkaListenerContainerFactory<String, Event> listenerFactory = new ConcurrentKafkaListenerContainerFactory<>(); listenerFactory.setConsumerFactory(consuemrFactory); listenerFactory.setConcurrency(3); listenerFactory.setRetryTemplate(retryTemplate()); listenerFactory.getContainerProperties().setPollTimeout(3000); return listenerFactory; }

Item

班级public class Item { private Type type; Item(Type type) { this.type = type; if (type == Type.PISTOL || type == Type.AR || type == Type.SNIPER_RIFLE) { this = new Weapon(type); } } } 继承自Weapon

Item

它从某个地方打来电话:

public class Weapon extends Item {

    Bullet.Type bulletType;
    int fireRate;

    public Weapon(Type type) {
        this.type = type;
    }
}

我实际上知道 Item item = new Item(Item.Type.PISTOL); 不能在Java中分配,但我想知道如何解决这种情况。

如果类型合适,我想指定this个新item

1 个答案:

答案 0 :(得分:5)

我建议用这种方式构建:

public static Item create(Type type) {
    if (type == Type.PISTOL || type == Type.AR || type == Type.SNIPER_RIFLE) {
        return new Weapon(type);
    } else {
        return new Item(type);
    }
}