Wednesday, 25th April 2012
Follow WikiJava on twitter now. @Wikijava

Generics: a stronger typization in Java5

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


I'd like to introduce you a very important forward leap towards a stronger typization in the Java 5 language: generics.

The Apple and Pear class are full working examples.

The TestApplePear class is a NOT working example, to show you the single most advantage from a stronger typization: a run-time error from the compiler.

Contents

the article

Comparable is a typical example of generic interface because it has a parameter of type T.

<T> is a declaration of formal parameter of type. After that declaration, T could be used in the code as a known type.

A generic class could be instantiated as in the following examples, and it will be clear that we can't compare pears and apples. Eheheh.

Comparable.java

public interface Comparable<T> {
 
    int compareTo(T o);
 
}

Apple.java

public class Apple implements Comparable<Apple>{
    private int weight;
    private String type;
 
    public Apple(String type, int weight) {
        this.type = type;
        this.weight = weight;
    }
 
    public int compareTo(Apple m){
        // we don't have to use an explicit cast
        return weight - p.weight;
    }
}

Pear.java

public class Pear implements Comparable<Pear>{
    private int weight;
    private String type;
 
    public Pear(String type, int weight){
        this.type = type;
        this.weight = weight;
    }
 
    public int compareTo(Pear p){
        // we don't have to use an explicit cast
        return weight - p.weight;
    }
}

TestApplePear.java

public class TestApplePear{
 
    public static void main (String [] args){
        Apple apple = new Apple("golden",135);
        Pear pear = new Pear("williams",120);
        int comp = pear.compareTo(apple); // compilation error
    }
}


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.