Java Generic Classes, how to define the constructor for possible parameter types

advertisements

I am trying to define a Java class which could be used for generic types, but I want to define the constructors for possible parameter types like Character, or an object type I can manually define.

The class I am trying to create is called:

public class Repeated<T> implements Pict {

private T[][] elements;

private double scale;

public Repeated(T[][] elems) {
    elements = elems;
}
}

So I want to add a constructor that adds a Character Array and does something specific if only T is the Type Character. Is it possible? Or should I make this an Interface, then implement it later?


So I want to add a constructor that adds a Character Array and does something specific if only T is the Type Character

Sounds like a good case for polymorphism:

public class RepeatedChars extends Repeated<Character> {

    public RepeatedChars(Character[][] chars) {
        super(chars);
        //do special stuff
    }

    //other character-specific logic if applicable
}

You could even hide this class as an implementation detail:

public class Repeated<T> implements Pict {

    ...

    private static class RepeatedChars extends Repeated<Character> {
        //see above
    }

    public static Repeated<Character> makeForChars(Character[][] chars) {
        return new RepeatedChars(chars);
    }
}