13

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?

2 Answers 2

16

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();
     }
}
2
  • 7
    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. Commented Oct 13, 2016 at 20:36
  • 4
    Ugh Java has supported covariants since Java 5. Apex why, why whyyyy?!!!
    – Strumbles
    Commented Sep 30, 2020 at 3:02
2

What interesting it works with interfaces.

✅ Interface

public interface Factory {
   SObject getRecord();
}

public class AccountFactory implements Factory {
    public Account getRecord() {
       return new Account(Name = 'Test');
    }
}

❌ Abstract/Virtual

Method return types clash: Account vs SObject from the type AccountFactory

public abstract class Factory {
   abstract SObject getRecord();
}

public class AccountFactory extends Factory {
    public override Account getRecord() {
       return new Account(Name = 'Test');
    }
}

There is idea for it since 2014 :(

https://ideas.salesforce.com/s/idea/a0B8W00000GdXOCUA3/support-covariant-return-types-in-apex

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .