简体   繁体   English

如何在抽象类中初始化泛型值?

[英]How to initialize a generic value in an abstract class?

I have a generic abstract class with a generic value, which I would like to mark final:我有一个具有通用值的通用抽象类,我想将其标记为 final:

public abstract class Value<T>
{
  final T value;

  static class StringValue extends Value<String>
  {
    StringValue (String value)
    {
      this.value = value + value;
    }
  }

  static class IntegerValue extends Value<Integer>
  {
    IntegerValue (Integer value)
    {
      this.value = value * value;
    }
  }

  public static void main (String[] args)
  {
    StringValue  s = new StringValue ("Hello");
    IntegerValue i = new IntegerValue (42);
  }
}

But this does not work:但这不起作用:

Value.java:9: error: cannot assign a value to final variable value
      this.value = value;
          ^
Value.java:17: error: cannot assign a value to final variable value
      this.value = value;
          ^
2 errors

The compiler forces me to initialize the generic value in the abstract class, but this does not make any sense, because the value is generic and can only be initialized in the derived classes.编译器强制我在抽象类中初始化泛型值,但这没有任何意义,因为值是泛型的,只能在派生类中初始化。

How to work around this problem?如何解决这个问题?

You need to either assign a final variable when declaring it or in the constructor of the class.您需要在声明它时或在类的构造函数中分配一个 final 变量。

It does not work with the constructor of child classes.它不适用于子类的构造函数。

However, the abstract class can have a constructor with the generic type as a parameter and use that.但是,抽象类可以有一个带有泛型类型作为参数的构造函数并使用它。

The child classes can then call the parent constructor:然后子类可以调用父构造函数:

public abstract class Value<T>
{
  final T value;
  protected Value(T value){
    this.value=value;
  }

  static class StringValue extends Value<String>
  {
    StringValue (String value)
    {
      super(value + value);
    }
  }

  static class IntegerValue extends Value<Integer>
  {
    IntegerValue (Integer value)
    {
      super(value * value);
    }
  }

  public static void main (String[] args)
  {
    StringValue  s = new StringValue ("Hello");
    IntegerValue i = new IntegerValue (42);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM