Ganesh
Ganesh

Reputation: 1654

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

Upvotes: 0

Views: 111

Answers (5)

Petar Ivanov
Petar Ivanov

Reputation: 93000

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;
    }   
}

Upvotes: 1

Mark Elliot
Mark Elliot

Reputation: 77024

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){...}
}

Upvotes: 1

dtech
dtech

Reputation: 14060

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.

Upvotes: 0

Cameron Skinner
Cameron Skinner

Reputation: 54276

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?

Upvotes: 2

Bohemian
Bohemian

Reputation: 424953

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");
}

Upvotes: 1

Related Questions