Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generics in abstract classes

Tags:

I'm working on an abstract class where the implementing class needs to implement a list of T. The problem is that this doesn't work:

public class AbstractClass {     public int Id { get; set; }     public int Name { get; set; }      public abstract List<T> Items { get; set; } }  public class Container : AbstractClass {     public List<Widgets> Items { get; set; } } 

I'm sure that there is an obvious answer that I'm missing, and I know that I can build an abstract base type to put in the list, but when I use my Linq command to build the list, the abstract type (ItemBase) doesn't play nicely with the .ToList() method. Is what I'm trying to do so unique?

like image 657
thaBadDawg Avatar asked Mar 01 '10 22:03

thaBadDawg


People also ask

Can abstract class have generic?

Luckily, we can use Java Generics. We can first declare an abstract class that uses generics T . Our generic T could refer to any class (i.e. String , Double , Integer , etc.). This is declared when the AbstractJob class is referenced.

What is the difference between abstract class and generic class?

Abstract is used to define something that requires additional definition of functionality before it is considered "complete" (or concrete in Java-certification-test-terms). Generic means it's a class that can handle a wide variety of data types that you define when you instantiate the class.

Is it a good idea to use generics in collections?

By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.


1 Answers

You need the declaration on the class as well, to know what type T is:

public abstract class AbstractClass<T> {     public int Id { get; set; }     public int Name { get; set; }      public abstract List<T> Items { get; set; } }  public class Container : AbstractClass<Widgets> {     public override List<Widgets> Items { get; set; } } 

You can also restrict what T can be, like say it must implement IWidgets:

public class AbstractClass<T> where T : IWidgets 
like image 54
Nick Craver Avatar answered Nov 09 '22 08:11

Nick Craver