Wolsie
Wolsie

Reputation: 144

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".

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

}
}

Upvotes: 0

Views: 108

Answers (2)

mh-dev
mh-dev

Reputation: 5503

Change the new part to

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

Upvotes: 1

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

you can´t do this, because SubInstance is inheriting from AbstractInstance<SubType>. Due to this you defined, that SubType is a AbstractInstance with the generic of SubType or any subclass of SubType.

But the variable AbstractInstance<AbstractType> abstractInstance doesn´t fullfill this condition.

Why? because not every AbstractType is a subclass of SubType. If you change the variable to be AbstractInstance<SubType> abstractInstance your programm will be compiling again

Upvotes: 3

Related Questions