Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariance and Overloading in Java

class A {    boolean f(A a) { return true; } } class B extends A {    boolean f(A a) { return false; } // override A.f(A)    boolean f(B b) { return true; }  // overload A.f }  void f() {      A a = new A();    A ab = new B();    B b = new B();    ab.f(a); ab.f(ab); ab.f(b); //(1) false, false, *false*    b.f(a); b.f(ab); b.f(b);    //(2) false, false, true } 

Can you please explain the first line last false output, why it is not true?

like image 423
nabil Avatar asked Jul 24 '12 06:07

nabil


People also ask

What is the covariant method overriding in Java?

Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any function if the return type is changed in the child class. But now it is possible only return type is subtype class.

What is covariance Java?

In Java, some array types are covariant and/or contravariant. In the case of covariance, this means that if T is compatible to U , then T[] is also compatible to U[] . In the case of contravariance, it means that U[] is compatible to T[] .

What is method overloading in Java?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.

What are covariant return types in Java why can we use them with overriding?

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.


2 Answers

can you please explain the first line last false output, why it is not true?

The compile-time type of ab is A, so the compiler - which is what performs overload resolution - determines that the only valid method signature is f(A a), so it calls that.

At execution time, that method signature is executed as B.f(A a) because B overrides it.

Always remember that the signature is chosen at compile time (overloading) but the implementation is chosen at execution time (overriding).

like image 59
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet


Well..because you are calling on type of A. So you can call only version of f(A a). that's returning false in B.

like image 39
Ahmad Avatar answered Sep 22 '22 02:09

Ahmad