68 What is Co-Variant return type in Java?

Code 1 :


class A
{
A m1()
{
return new A();
}
}

class B extends A
{
/* Valid
A m1()
{
return new A();
}
*/

B m1()
{
return new B();
}


}

class Test
{
public static void main( String args[] )
{
System.out.println(" Coding Atharva ");

B obj = new B();
System.out.println( obj.m1() );
}
}


Output:


Co-Variant Return Type in Java



Code:

import java.io.*;

class A
{
Object m1()
{
return new Object();
}
}

class B extends A
{
@Override
String m1()
{
return new String(" Atharva ");
}

}

class Test
{
public static void main( String args[] )
{
System.out.println(" Coding Atharva ");

B obj = new B();
System.out.println( obj.m1() );
}
}


Output:


Co-Variant

Previous
Next Post »