Sarthak Shrivastava
Sarthak Shrivastava

Reputation: 13

Interfaces as parameters (Restrictions)

I came across an AP CSA question which had me puzzled for a while. It was basically an incomplete method that looked like this:

public static void methodMan(Comparable c) {.....}

The question first asked if it was valid to use the comparable interface in the parameter listing, then it asked if there were any restrictions on the comparable object. I was stuck between the choices that said either the object c that is being passed needs to be casted or initialized as a comparable or the object c could be any object that implements the comparable interface. Which one is it, and if it isn't either, what would be a restriction on the object c?

Upvotes: 1

Views: 64

Answers (2)

user unknown
user unknown

Reputation: 36229

compiles like a charm:

public static void methodMan (Comparable c) {
    out.println ("we ignore c");
}

public static void main (String args[])
{
    Comparable c1 = new String ();
    methodMan (c1);
    methodMan ((Comparable) c1);
    String s2 = new String ();
    methodMan (s2);
    methodMan ((Comparable) s2);
}

and runs like a charm.

Upvotes: 0

locus2k
locus2k

Reputation: 2935

Yes it is valid to use interfaces as a parameter in methods and yes object c can be any object that implements the interface. The only caveat to the second portion is if there is a special method that needs to be invoked that the interface does not implement then you will need to cast it to the class first to get the method For Example:

public class MyComparable implements Comparable<String> {

  private String item;

  public MyComparable(String item) {
    this.item = item;
  }

  @Override
  public int compareTo(String o) {
    return this.item.compareTo(o);
  }

  public Integer doThis() {
    return 100;
  }

  public Integer compareSample(Comparable<String> c) {
    if (c instanceof MyComparable) {
      return ((MyComparable)c).doThis();
    }
    return c.compareTo(this.item);
  }

}

Upvotes: 1

Related Questions