Wednesday, October 3, 2012

Java Tidbits ....................5(Covariant)

  •  An overriding method, should define exactly same set of argument list, as the overridden method, or else we will end up defining an overloaded method. This includes the covariant data types, i.e., if any argument in the overriding method is a subclass of the argument defined in the super class, we will end up defining an overloaded method.
  •  A valid overriding method can define a return type, which is a subclass of the return type defined by the Overridden method in the super class. 
Run this example  and tweak your brain.
---------------------------------------------------------------------------------
class TestB{
    int kk=9;
    public  Object mytest(Object o)
    {
        System.out.println("ok in Base");
        return o;
    }
}

public class TestA extends TestB{
   
    int kk =8;
   
    public  String mytest(Object o )
    {
        System.out.println("ok in overloaded sub class");
        return o.toString();

    }
    public  void mytest(String o )
    {
        System.out.println("ok in sub class");

    }
    public static void main(String args[])
    {
      
        TestB tb = new TestB();
        TestA ta = new TestA();

        
        ta.mytest("ok");
        tb.mytest("ok");
        System.out.println(" ta.kk = "+ ta.kk + "tb.kk = "+tb.kk);
      
        tb = new TestA();
        tb.mytest("ok");
        System.out.println("tb.kk = "+tb.kk);

      
        System.exit(0);

     }

For more examples on covariant types refer >>
http://cafe4java.com/mockexams/scjp/mock1/q1.php

No comments: