Assume we have a Parent interface with compare() function.
public interface Parent {
public int compare(Parent otherParent);
}
Suppose that children Child1, Child2, Child3 implement this interface Parent
public class Child1 implements Parent {
@Override
public int compare(Parent other) {
Child1 otherChild = (Child1)other;
}
}
Also, I am using generics <T extends Parent>
everywhere else in the code. So I need to compare two objects of type T from other parts of code.
I understand this is a bad design as I am typecasting the Parent object in compare() function and I don't even know whether the input is of type Child1.
How can I avoid this type casting while using generics?
Interfaces formalize polymorphism. Interfaces allow us to define polymorphism in a declarative way, unrelated to implementation. Two elements are polymorphic with respect to a set of behaviors if they realize the same interfaces.
Casting an object does not change the object to the object being cast, but allows another class reference that is related to it by inheritance to refer to the object. For example C extends E .
– Casting a reference variable v does not change its static type.
Why not this?
interface Parent<T extends Parent<?>> {
int compare(T type);
}
class Child1 implements Parent<Child1>{
@Override
public int compare(Child1 type) {
return 0;
}
}
Edit: To insure correct usage you can use
interface Parent<T extends Parent<T>>{ /* ... */ } //instead of wildcard
But to be honest that "loop" doesn't look pretty, and since Generics in Java don't work at RunTime (more information), they're essentially syntactic-sugar for that same cast you called "bad design" so I don't think your current approach is bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With