java Generic Type vs Abstract class for parameter

5.3k views Asked by At

I'm studying Java Generic type.

I have the abstract class AbstractInputdata.

public abstract class AbstractInputData {
....
}

Some class that extend AbstractInputData

public class Email extends AbstractInputData{
...
}
public class Mobile extends AbstractInputData{
...
}
......

A.

public class ProcessorA {
public static boolean isCustomData(AbstractInputData abstractInputData) {
....
}
}

B.

public class ProcessorB {
public static <T extends AbstractInputData> boolean isCustomData(T t) {
...
}
}

Is there any difference between A and B?

2

There are 2 answers

1
Peter Lawrey On

The only difference is that the second method with appear as a generic typed method via Reflections. It's behaviour will be the same except in odd cases like this

processorB.<MyType>isCustomData(t); // won't compile unless t is a MyType

You would have to tell it what type you expect it to match, which isn't that useful IMHO.

1
TomWolk On

Since your methods only produce a boolean, there is no difference. But in case you want to return the input you can use B to preserve the generic type:

public class ProcessorB {
  public static <T extends AbstractInputData> boolean isCustomData(T t) {
    ...
  }
  public static <T extends AbstractInputData> T copyCustomData(T t) {
    ...
  }
}

ProcessorA could only return an object of type AbstractInputData while processorB returns Email or Mobile depending on the parameter type.