Reputation: 509
I have the following hierarchy of classes
public abstract class MyAbstractClass {
}
public abstract class AbstractClassA extends MyAbstractClass {
}
public class AbstractClassB extends MyAbstractClass {
}
public class ClassA extends AbstractClassA {
}
public class ClassB extends AbstractClassA {
}
I have a converter which should accept instance of a class
extending AbstractClassA
and should return instance
of a class
extending AbstractClassB
. I have two versions of conversion class one using Generic and the other one is not. Both works fins. But what is the correct way of specifying the signature of the converter?
public class ConverterTwo {
public AbstractClassB convert(AbstractClassA a) {
}
}
public class ConverterOne {
public <A extends AbstractClassA, B extends AbstractClassB> B convert(A a) {
}
}
Upvotes: 3
Views: 115
Reputation: 178
Generics are checked only at compile time and are replaced with the proper types during compilation.
ConverterTwo
code will be converted to ConverterOne
kind of code during compilation and thus both are equivalent.
Generics are especially useful when you write an API where you do not know what kind of objects the consumer of the API's are going to pass. In your case, if you plan to write a generic adapter.
Classic example of genrics : Collection Interface and the classes that implement it.
Upvotes: 1
Reputation: 4300
Both are correct but my suggestion is go with ConverterTwo
which is simpler. You can always Generify and make a Generic Interface or Abstract class out of your Converter later.
Upvotes: 0
Reputation: 840
Both are correct ways. It's just that ConverterTwo
class has less code in signature as compared to ConverterOne
. Also both the syntax AbstractClassA
and <A extends AbstractClassA>
will behave in same manner in this example.
Upvotes: 0
Reputation: 47290
Use 1, you have all the type checking you need because the parameters extend an abstract class. And its less code than 2, which always a good thing. But neither would be wrong.
Upvotes: 0