/java/

Java Generics

2013-01-17 22:43:46

Cameleon

<apple> cameleon1 
= new Cameleon<apple>( new Apple() );
Apple aple1 = cameleon1.getBody();
aple1.grow();

CameleonOld cameleon2 
= new CameleonOld( new Apple() );
Apple aple2 = (Apple) cameleon2.getBody();
aple2.grow();
public class Cameleon<t> {
    private T body;

    public Cameleon() {

    }

    public Cameleon(T body) {
        this.body = body;
    }

    public T getBody(){
        return this.body;
    }

    public void set(T body){
        this.body = body;
    }

    @Override
    public String toString() {
        return this.body.getClass()+" / "+super.toString();
    }   
}

public class CameleonOld {
    private Object body;

    public CameleonOld() {

    }

    public CameleonOld(Object body) {
        this.body = body;
    }

    public Object getBody(){
        return this.body;
    }

    public void set(Object body){
        this.body = body;
    }

    @Override
    public String toString() {
        return this.body.getClass()+" / "+super.toString();
    } 
}