Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics: Inheriting from an abstract class that implements an interface

Tags:

I have the following interface:

public interface SingleRecordInterface<T> {     public void insert(T object); } 

I have the abstract class below (that does not mention the method insert):

public abstract class AbstractEntry implements SingleRecordInterface<AbstractEntryBean> { } 

I have the concrete class:

public class SpecificEntry extends AbstractEntry {     public void insert(SpecificEntryBean entry) {         // stuff     } } 

Finally, SpecificEntryBean is defined as:

public class SpecificEntryBean extends AbstractEntryBean { } 

I have the following error:

The type SpecificEntry must implement the inherited abstract method SingleRecordInterface.insert(AbstractEntryBean)

I don't understand the reason for this error, given that SpecificEntryBean extends AbstractEntryBean. How do I fix this error?

like image 328
Matt Avatar asked Mar 27 '12 16:03

Matt


People also ask

Can you inherit from an abstract class and an interface?

An abstract class defines the identity of a class. An interface can inherit multiple interfaces but cannot inherit a class. An abstract class can inherit a class and multiple interfaces.

Can you inherit from an abstract class?

An abstract class cannot be inherited by structures. It can contain constructors or destructors. It can implement functions with non-Abstract methods. It cannot support multiple inheritances.

Can a generic implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.


2 Answers

You need to make your abstract class generic as well:

public abstract class AbstractEntry<T extends AbstractEntryBean> implements SingleRecordInterface<T> { } 

Then for your concrete class:

public class SpecificEntry extends AbstractEntry<SpecificEntryBean> { } 
like image 187
Alex Avatar answered Oct 23 '22 05:10

Alex


Change to the following:

public abstract class AbstractEntry<EB extends AbstractEntryBean> implements SingleRecordInterface<EB> { } 

and

public class SpecificEntry extends AbstractEntry<SpecificEntryBean> {     public void insert(SpecificEntryBean entry) {         // stuff     } } 
like image 44
Guillaume Polet Avatar answered Oct 23 '22 04:10

Guillaume Polet