0
public interface myInterface<T> {

    public List<T> doWork();

}

public abstract class baseClass<T> implements myInterface<T>{

    protected T obj;
    protected List<T> list;

    public baseClass<T>(){
         //how do I initiate obj?
         //how do I initiate list?
    }   
}

public class myClassA extends baseClass<T> {

 public List<T> doWork()
}

I have this code and I was wondering how I could initiate obj and list of type T dynamically.

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

2 Answers2

0

You don't have to initialize anything in BaseClass because it is abstract. But, you certainly can do it. And, name the class with a capital B and the interface with a capital M, as that's the standard. What you don't need to do is to put the <T> in the constructor. Here's one possibility:

public BaseClass(T obj, List<T> list){
    this.obj = obj;
    this.list = list; // Or copy it for safety. 
}   

If you want the list to be created by the class itself, initialize it at its declaration:

protected List<T> list = new ArrayList<>();  // Java 7
public BaseClass(T obj){
    this.obj = obj;
}   
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
0

In general, with generics, you will pass in the typed object to be used when constructing your generic object (or maybe a factory which knows how to create them).

Anything else is a hack which requires more knowledge of the type than the compiler can tell, like using "reflection" to create an object assuming it has a 0-argument constructor (you should never do this, or at least not until you are really sure you know what is going on -- in which case it is very unlikely you will want to do it).

Shadow Man
  • 3,234
  • 1
  • 24
  • 35