Skip to main content

Posts

Showing posts with the label Covariant method

Covariant methods

Normally when we override a function(method) in a derived class, this overriding function must have the same signature as the function in base class. But in Java, the overriding method can have a different return type provided this return type is the sub-class of return type in overridden method. Such methods are called Covariant methods. e.g class Ret1{....} class B {     Ret1 foo(int n){       .......     } } class Ret2 extends Ret1{.....} class C extends B{      Ret2 foo(int n){         ....     } } In the derived class C, we are overriding the function foo. Return type of foo() in base class is Ret1 and return type of foo() in derived class is Ret2. This is valid because, Ret2 is a sub-class of Ret1. Let us look at a complete example. class Number { Number ( int n ) { this . n = n ; } int n ; } clas...