Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Covariants

Tags:

java

public class CovariantTest {
    public A getObj() {
        return new A();
    }

    public static void main(String[] args) {
        CovariantTest c = new SubCovariantTest();
        System.out.println(c.getObj().x);
    }
}

class SubCovariantTest extends CovariantTest {
    public B getObj() {
        return new B();
    }
}

class A {
    int x = 5;
}

class B extends A {
    int x = 6;
}

The above code prints 5 when compiled and run. It uses the covariant return for the over-ridden method.

Why does it prints 5 instead of 6, as it executes the over ridden method getObj in class SubCovariantTest.

Can some one throw some light on this. Thanks.

like image 953
DonX Avatar asked Jan 01 '09 10:01

DonX


People also ask

What are covariant in Java?

Covariant return type refers to return type of an overriding method. It allows to narrow down return type of an overridden method without any need to cast the type or check the return type. Covariant return type works only for non-primitive return types.

How is covariant return type implemented in Java?

How is Covariant return types implemented? Java doesn't allow the return type-based overloading, but JVM always allows return type-based overloading. JVM uses the full signature of a method for lookup/resolution. Full signature means it includes return type in addition to argument types.

What is Contravariant return type?

More specifically, covariant (wide to narrower) or contravariant (narrow to wider) return type refers to a situation where the return type of the overriding method is changed to a type related to (but different from) the return type of the original overridden method.

Is it possible to override co variant return types?

Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child's return type should be a subtype of the parent's return type. The overriding method becomes variant with respect to return type.


1 Answers

This is because in Java member variables don't override, they shadow (unlike methods). Both A and B have a variable x. Since c is declared to be of type CovarientTest, the return of getObj() is implicitly an A, not B, so you get A's x, not B's x.

like image 75
Lawrence Dol Avatar answered Oct 17 '22 06:10

Lawrence Dol