简体   繁体   English

抽象类与抽象泛型?

[英]Abstract Class with Abstract Generics?

I'm having an issue when using an abstract class with abstract generics. 将抽象类与抽象泛型一起使用时遇到问题。

I can instantiate the subclass, but I can't then refer to it as the abstract supertype. 我可以实例化该子类,但是不能将其称为抽象超类型。

For example: 例如:

AbstractInstance<AbstractType> instance = new SubInstance()

Where 哪里

SubInstance extends AbstractInstance(SubType)

Gives me "cannot convert from SubInstance to AbstractInstance". 给我“无法从SubInstance转换为AbstractInstance”。

What am I doing wrong? 我究竟做错了什么? Proper example included below. 正确的示例如下。

public class Demo
{
/**
 * Abstract Instance
 *
 * @param <Type>
 */
public abstract class AbstractInstance<Type extends AbstractType>
{

}

/**
 * Abstract Generic Type
 *
 */
public abstract class AbstractType
{

}

/**
 * Sub Instance that extends AbstractInstance
 *
 */
public class SubInstance extends AbstractInstance<SubType>
{

}

/**
 * SubType that extends AbstractType
 *
 */
public class SubType extends AbstractType
{

}

public static void main(String[] args)
{
    //Type mismatch: cannot convert from Demo.SubInstance to Demo.AbstractInstance<Demo.AbstractType>
    AbstractInstance<AbstractType> abstractInstance = new SubInstance();

}
}

you can´t do this, because SubInstance is inheriting from AbstractInstance<SubType> . 您不能执行此操作,因为SubInstanceAbstractInstance<SubType>继承。 Due to this you defined, that SubType is a AbstractInstance with the generic of SubType or any subclass of SubType . 由于这一点,你定义, SubTypeAbstractInstance与通用的SubType或的任何子类SubType

But the variable AbstractInstance<AbstractType> abstractInstance doesn´t fullfill this condition. 但是变量AbstractInstance<AbstractType> abstractInstance满足此条件。

Why? 为什么? because not every AbstractType is a subclass of SubType . 因为不是每个AbstractType都是SubType的子类。 If you change the variable to be AbstractInstance<SubType> abstractInstance your programm will be compiling again 如果将变量更改为AbstractInstance<SubType> abstractInstance您的程序将再次编译

将新零件更改为

AbstractInstance<? extends AbstractType> abstractInstance = new SubInstance();

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

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