0

First actual post here.

I am fairly new to Apex Classes and I'm working on an existing project.

The previous developer has the following inside of an apex class:

private List<id> accountsMainList = new List<id>();
Boolean archiveSync = false;
public BDGAccSync(Boolean archiveSync) {
    this.archiveSync = archiveSync;
}
public BDGAccSync(List<Account> accountsMainList) {
    for (Account acc : accountsMainList) {
        this.accountsMainList.add(acc.id);
    }
}

My question is - Does the second instance override the first or does Salesforce support overloading like java, etc?

UPDATE: Thank you all for the quick answers 🙌 Overloading it is!

2
  • Apex allows many patterns present in Java including method and constructor overloading.
    – Keith C
    Commented Jan 28 at 17:33
  • N.B. You can simplify the second constructor to this.accountsMainList.addAll(accountsMainList); and eliminate the for loop
    – cropredy
    Commented Jan 28 at 19:10

1 Answer 1

2

That's a pretty standard practice (in programming in general, not just Salesforce/Apex) called overloading.

You have the same constructor (or method) name, but just pass in a different number or different types of arguments.

You'll only end up using one of the two constructors at any given time that you call new BDGAccSync(...);. As long as you pass appropriate arguments to it, the correct version will automatically be called. I.e. new BDGAccSync(false); will call the version that takes a Boolean and not the one that takes a List<Account> without any other intervention from you.

You must log in to answer this question.

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