This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Friday, February 19, 2010

31 - Covariant Return - Java 1.6

They use several time a covariant return in the master exams... Be careful...

I find the explanations here interesting

Example :

1) Java 1.1 and after (this will compile) - It is NOT a covariant return !!!


package covariantreturn;

public class A {
    A method() {
        return this;
    }
}

package covariantreturn;

public class B extends A {
    A method() {
        return this;
    }
}

package covariantreturn;

public class C extends B {
      A method() {
        return this;
    }
}

2a) Java 1.5 and after (will not compile in Java < 1.5 !!!) - Covariant Return !
You return a subtype of A in B
You return a subtype of B in C (can be B) 


package covariantreturn;

public class A {
    A method() {
        return this;
    }

}

package covariantreturn;

public class B extends A {
    B method() {
        return this;
    }
}

package covariantreturn;

public class C extends B {
      B method() {
        return this;
    }
}

2b) 

You return a subtype of A in B
You return a subtype of B in C (can be C) 

package covariantreturn;

public class A {
    A method() {
        return this;
    }

}

package covariantreturn;

public class B extends A {
    B method() {
        return this;
    }
}

package covariantreturn;

public class C extends B {
      C method() {
        return this;
    }
}

No comments:

Post a Comment

Followers