Method return types clash? Does Apex support covariant return types?

I have a class inheritance as follows.

public virtual class A{
   public virtual A myMethod(){
      return new A();
   }
}

public class B extends A{
   public override B myMethod(){
      return new B();
   }
}

But it throws an compile error:

Method return types clash: myMethod()

And my question is How to return child type instead of father type when overriding a method?

Answer

You can’t alter the return type for overridden methods. Either return the parent type, which you can then cast to the child type, if it is a child, or simply return it as an Object (which is how various methods like JSON.deserialize works). In either case, you’ll need to do casting at least some of the time.

Example:

public class B extends A {
    public override A construct() {
        return new B();
     }
}

Attribution
Source : Link , Question Author : Jun Ke , Answer Author : sfdcfox

Leave a Comment