开发者

How to proceed using Generics in java

I have a interface

public interface Doable<T,U> {
    public U doStuff(T t);
}

I have an abstract class which implements Doable<T,U>

public 开发者_如何学运维abstract class AbstractDoable<T,U> implements Doable<T, U> {
    private SomeClass someClass;

}

Now I need to implement the above classes, but I need to use different classes for T and U.

Please suggest how should I proceed in this as I will need to have multiple implemetations of AbstractDoable with different T and U. For example:

ConvertDoable<String,Integer> extends AbstractDoable

or

ConvertDoable<A,B> extends AbstractDoable


You can create whatever subclasses of Doable or AbstractDoable you want. For example:

public class DoNothing implements Doable<String, String> {
    public String doStuff(String input) {
        return input;
    }
}

or

public class DoSomething extends AbstractDoable<Integer, String> {
    public String doStuff(Integer i) {
        return i.toString();
    }
}

I'm not sure what the purpose of your someClass member is in AbstractDoable. Can you explain what it is for?


If you're worried about class bloat, consider anonymous classes - classes defined "on the fly" as you need them:

public static void main(String[] args) {
    Doable<String, Integer> myDoable = new AbstractDoable<String, Integer>() {
        public Integer doStuff(String t) {
           return new Integer(t); // for example
        }
    }

    Integer i = myDoable.doStuff("0");
}


Your concrete implementations should either specify the types on AbstractDoable

public class ConvertDoable extends AbstractDoable<String,Integer>
{
    public Integer doStuff(String arg){...}
}

or continue to pass along parameterized generics:

public class ConvertDoable<T,U> extends AbstractDoable<T,U>
{
    public U doStuff(T arg){...}
}


interface Doable<T,U> {
    public U doStuff(T t);
}

abstract class AbstractDoable<T,U> implements Doable<T, U> {
}

class ConvertDoableStringInteger extends AbstractDoable<String, Integer>{
    public Integer doStuff(String t) {
        return null;
    }   
}

class ConvertDoableIntergerFloat extends AbstractDoable<Integer, Float> {
    public Float doStuff(Integer t) {
        return 0.0f;
    }   
}


The whole idea about generics is that you make a single class which supports all types of classes (or at least all classes who inherit from a class or implement an interface).

Also in Java (bytecode) there is no difference between say

GenericClass<A,B> foo;

and

GenericClass<C,D> bar;

You thus need to define a single class that can handle all the different objects that might be given to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜