View RSS Feed

Advanced Java

Use an Interface to Compare Objects in Generics

Rating: 1 votes, 1.00 average.
by , 11-29-2011 at 11:25 PM (2234 Views)
A key aspect of using generics is being able to compare different objects. Consider an example where you are comparing different species of felines.
Java Code:
public class ComparableFeline implements Comparable<ComparableFeline> {

	@Override
	public int compareTo(ComparableFeline arg0) {
		return 0;
	}
}
So if you wanted to narrow ComparableFeline for use only among different types of domesticated cats instead of other felines such as lions, tigers, it would produce a compile time error. The reason being that once ComparableFeline is implemented for Comparable, no other implementing class can be compared to anything but a ComparableFeline.

So the proper way to is to re-implement the same interface of ComparableFeline including the parameter types. It is basically the same as overriding the methods in the base class.

Java Code:
public class WildCat extends ComparableFeline {
	private static int numberOfWildCats = 0;
	private int id;
	private String name;
	
	public WildCat() {
		super();
		id = ++numberOfWildCats;
		name = "wildcat" + id;
	}

	public String getName() {
		return name;
	}

	public int compareTo(ComparableFeline arg0) {
		return super.compareTo(arg0);
	}

	public int id() {
		return id;
	}
}


public class JungleCat extends ComparableFeline {

	public int compareTo(ComparableFeline arg0) {
		return super.compareTo(arg0);
	}
}

Submit "Use an Interface to Compare Objects in Generics" to Facebook Submit "Use an Interface to Compare Objects in Generics" to Digg Submit "Use an Interface to Compare Objects in Generics" to del.icio.us Submit "Use an Interface to Compare Objects in Generics" to StumbleUpon Submit "Use an Interface to Compare Objects in Generics" to Google

Updated 11-30-2011 at 08:37 AM by Advanced Java

Categories
Generics

Comments