2

I have a generic class which extends another generic class.

The abstract class has 2 type parameters, but I need only one in my functions.

Is it save to just assign it a random like String type, or are there any drawbacks to this?

public abstract class AbstractFoo<T, B>
{
   public abstract void read(T item);
}

public class LittleFoo extends AbstractFoo<byte[], String>
{
   @Override
   public void read(byte[] item)
   {
      // work here
   }
}
2
  • If you want just one generic parameter, then why you have declared 2 at the first place? Commented Nov 20, 2012 at 18:26
  • Because I have multiple classes inheriting from this one by design. Only a few special classes only need 1 parameter. Commented Nov 20, 2012 at 18:31

2 Answers 2

5

Or you can use java.lang.Void instead of String.

Sign up to request clarification or add additional context in comments.

Comments

3

No there really isn't any drawback to this, and it seems like a simple way to do it in my opinion.

Also, you might want to consider using composition instead of extension. For example, take a look at the HashSet implementation from java.util:

87   public class HashSet<E>
88       extends AbstractSet<E>
89       implements Set<E>, Cloneable, java.io.Serializable
90   {
91       static final long serialVersionUID = -5024744406713321676L;
92   
93       private transient HashMap<E,Object> map;
94   
95       // Dummy value to associate with an Object in the backing Map
96       private static final Object PRESENT = new Object();

A HashSet is basically a HashMap, but only considers the set of keys (hence the dummy variable PRESENT, which is just a placeholder). You could perhaps do something similar.

1 Comment

Very informative answer, thanks. Actually I'm using both, my classes have other children of AbstractFoo as fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.