Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Polymorphism : How can I avoid type casting input parameters?

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?

like image 916
Ajay Gupta Avatar asked Jul 24 '16 11:07

Ajay Gupta


People also ask

Can we use interface handle to achieve polymorphism?

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.

What is casting objects in polymorphism?

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 .

Does casting change the static type?

– Casting a reference variable v does not change its static type.


1 Answers

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.

like image 170
Pedro David Avatar answered Sep 23 '22 00:09

Pedro David