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?


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.


public class B extends A {
    public override A construct() {
        return new B();
  • 3
    Ohhh, I stack with this restriction. It is one of the key feature of OPP languages like Java, for example. I can't understand why Apex can't do that , because everything working on the JVM, and if I clear it have 6 version. Oct 13 '16 at 20:36
  • Ugh Java has supported covariants since Java 5. Apex why, why whyyyy?!!!
    – Strumbles
    Sep 30 '20 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.