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?
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.
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[] .
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With