Oloff Biermann
Oloff Biermann

Reputation: 716

Not Completely Sure About Why to Use Polymorphic Reference

Ok so basically I have generic type T here which implements Comparable interface. Now say you want to iterate over an array of T objects. I've seen examples where you use T reference when iterating and other examples where you have Comparable reference, which is possible since T implements Comparable.

My question is, why would you choose one other the other; is there any real practical reason for choosing Comparable reference rather than T?

The example shows iteration over array, one with Comparable reference, other with T reference.

public static <T extends Comparable<T>> 
        void baz(T[] biz)
{

    for (Comparable d: biz)
    {
        System.out.println(d); //Comparable reference
     }

    for (T foo: biz)
    {
      System.out.println(foo); //T reference        
    }
}

Upvotes: 0

Views: 37

Answers (2)

C. K. Young
C. K. Young

Reputation: 223003

In the case of System.out.println, it takes Object, which both Comparable<T> and T satisfy (since all objects are instances of Object), so you could have written for (Object foo : biz) and it'd have worked in this case.

In the general case, choose the most general type that works for the operations you need to invoke.

Upvotes: 1

Jason
Jason

Reputation: 11832

Use the Comparable reference only when you want to compare the objects. Otherwise use the T reference, since you may want to pass the object to some other method that takes a T object.

Remember, standard inheritance rules apply here - you can cast a T reference to Comparable (because you specified that T must extend Comparable), but you can't cast every Comparable reference to T.

Upvotes: 0

Related Questions